#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
import calendar
import common
import pylibmc
import hashlib
import os.path
import sys
reload(sys) 
sys.setdefaultencoding('utf8')
from tornado.web import RequestHandler
import pymongo
import redis
import re
import render
import cnsort
import codecs
from _base import BaseHandler
import datetime
sys.path.insert(0,'/home/liuyue/svn/wan/')
sys.path.insert(0,'/opt/wanalytics/')
from Tools import getPid
from Tools import connectMySQL 
import json
import json_ly
from util import cache, settings
import _clientCache as clientcache
import _clientUser as clientuser
import logging
import time
import tornado.ioloop
import settings
import MySQLdb
import csv



class MainClient(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
        os_json = clientcache.getOS()
        
        pidtype_json = clientcache.getPidType()
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        try:
            st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
        except :
            self.send_error(400, desc='invalid argument')
            #self.write({"status": "failed", "code": 400,  "desc": "invalid argument"})
            #self.finish()
            return
        
        if not _pd:
            ed_time = datetime.datetime.now()
            delta = ed_time - st_time 
            _pd =  abs(delta.days)
        
        _pd = int(_pd)
        et_time = st_time + datetime.timedelta(days=_pd)
        st_datestr = st_time.strftime('%Y%m%d')
        et_datestr = et_time.strftime('%Y%m%d')
        
        all_data = []
        results = {}
        os_data = []
        
        
        
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        _md5_ = _md5.hexdigest()
        m_value = mc.get(_md5.hexdigest()) or {}
        if settings.cache_on == 0:
            m_value = {}
            
        if not m_value:
        
        
        
        
            #connection = pymongo.Connection("10.103.13.42", 27017)
            #db = connection.DailyLog
            db = connectMySQL.connMySQL_stat()
            c=db.cursor()
            #sql = "SELECT date, os, type, pv, uv, vv  FROM `view_day_mainAnalytics` WHERE date>= '{0}' and date < '{1}'".format(st_datestr, et_datestr)
            #sql = "SELECT date, os_id, pid_type, pv, uv, vv  FROM `viewdaymain` WHERE date>= '{0}' and date < '{1}'".format(st_datestr, et_datestr)
            sql = "SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser)  FROM `stat_day_total_collect` WHERE date>= %s and date < %s and  business_type=1 and pid_stat=1   %s   group by date, os_id, device_type " % (st_datestr,et_datestr,common.clear_date())
            logging.info(sql)
            print sql
            c.execute(sql)  
            res= c.fetchall()
            _tmpdate = ''
            for x in res:
                date = str(x[0])
                os = os_json.get(int(x[1])) or 'null'
                #type1 = pidtype_json.get(int(x[2])) or 'null'
                if int(x[1]) != 72:
                    type1 = settings.device_type.get(str(x[2])) or 'unkown'
                else :
                    type1 = ''
                pv = int(x[3])
                uv = int(x[4])
                vv = int(x[5])
                nu = int(x[6])
                
                if _tmpdate and _tmpdate != date:
                    results['data'] = os_data
                    results['year'] = _tmpdate[:4]
                    results['month'] = _tmpdate[4:6]
                    results['day'] = _tmpdate[6:]
                    all_data.append(results)
                    results = {}
                    os_data = []
                
                #if os == "Android" and type1 == "Phone":
                os_data.insert(0,{'os':os, 'type':type1, 'pv':pv, 'uv':uv, 'vv':vv, 'nu': nu})
                _tmpdate = date
            
            c.close()
            db.close()
            
            if len(os_data) > 0 :
                results['data'] = os_data
                results['year'] = _tmpdate[:4]
                results['month'] = _tmpdate[4:6]
                results['day'] = _tmpdate[6:]
                all_data.append(results)
                results = {}
                os_data = []
            try:
                mc.set(_md5_,all_data)
            except:
                pass
                
        else:
            all_data = m_value

        self.write({"status":"success", "items":all_data})
        self.finish()
        


class StartActive(BaseHandler):
    def get(self):
        _type = self.get_argument('type','week').strip()
        _pingtai = self.get_argument('pingtai','Video').strip()
        
        db = connectMySQL.connMySQL_stat()
        c=db.cursor()
        
        
        c.execute(" select %s_period,%s_number from `stat_activeUser_%s` order by %s_number desc limit 1 " % (_type,_type,_type,_type))  
        result = c.fetchone()
        enddate = result[0]
        en = result[1]
        c.execute(" select %s_period,%s_number from `stat_activeUser_%s` where %s_number = %s limit 1 " % (_type,_type,_type,_type,(en-3)) )  
        result = c.fetchone()
        if result == None:
            c.execute(" select %s_period,%s_number from `stat_activeUser_%s` where %s_number <= %s order by %s_number asc limit 1 " % (_type,_type,_type,_type,en,_type) )  
            result = c.fetchone()
            startdate = result[0]
            sn = result[1]
        else:
            startdate = result[0]
            sn = result[1]
        
        if _type == "week":
            
            enddate_list = enddate.split("-")
            endate_str = enddate_list[0] 
            yy = endate_str[0:4]
            mm = endate_str[4:6]
            ec = "%s%s" % (yy,mm)
            
            sql = " select distinct(%s_period) from `stat_activeUser_%s` where %s_period like '%s%%' order by %s_number asc " % (_type,_type,_type,ec,_type)
            
            #print sql
            c.execute(sql)  
            result = c.fetchall()
            etable = ""
            if result == None:
                etable += "<a per='%s' onclick=\"changehuoyuebox('%s','%s','%s','%s','%s')\" href=\"javascript:;\">%s(%s)</a><br />" % (enddate,_pingtai,_type,'End',enddate,cnsort.huoyuez(enddate),cnsort.huoyuez(enddate),enddate)
            else:
                for x in result:
                    etable += "<a per='%s'  onclick=\"changehuoyuebox('%s','%s','%s','%s','%s')\" href=\"javascript:;\">%s(%s)</a><br />" % (x[0],_pingtai,_type,'End',x[0],cnsort.huoyuez(x[0]),cnsort.huoyuez(x[0]),x[0])
            
            
            startdate_list = startdate.split("-")
            startdate_str = startdate_list[0] 
            yy = startdate_str[0:4]
            mm = startdate_str[4:6]
            sc = "%s%s" % (yy,mm)
                    
            c.execute(" select distinct(%s_period) from `stat_activeUser_%s` where %s_period like '%s%%' order by %s_number asc  " % (_type,_type,_type,sc,_type) )  
            result = c.fetchall()
            stable = ""
            if result == None:
                stable += "<a per='%s' onclick=\"changehuoyuebox('%s','%s','%s','%s','%s')\" href=\"javascript:;\">%s(%s)</a><br />" % (startdate,_pingtai,_type,'Start',startdate,cnsort.huoyuez(startdate),cnsort.huoyuez(startdate),startdate)
            else:
                for x in result:
                    stable += "<a per='%s' onclick=\"changehuoyuebox('%s','%s','%s','%s','%s')\" href=\"javascript:;\">%s(%s)</a><br />" % (x[0],_pingtai,_type,'Start',x[0],cnsort.huoyuez(x[0]),cnsort.huoyuez(x[0]),x[0])

        
        else:
            sql = " select distinct(%s_period) from `stat_activeUser_%s` where %s_number < %s order by %s_number asc  limit 5 " % (_type,_type,_type,en,_type)
            
            #print sql
            c.execute(sql)  
            result = c.fetchall()
            etable = ""
            if result == None:
                etable += "<a per='%s' onclick=\"changehuoyuebox('%s','%s','%s','%s','%s')\" href=\"javascript:;\">%s(%s)</a><br />" % (enddate,_pingtai,_type,'End',enddate,cnsort.huoyuez(enddate),cnsort.huoyuez(enddate),enddate)
            else:
                for x in result:
                    etable += "<a per='%s'  onclick=\"changehuoyuebox('%s','%s','%s','%s','%s')\" href=\"javascript:;\">%s(%s)</a><br />" % (x[0],_pingtai,_type,'End',x[0],cnsort.huoyuez(x[0]),cnsort.huoyuez(x[0]),x[0])
                    
            c.execute(" select distinct(%s_period) from `stat_activeUser_%s` where %s_number < %s order by %s_number asc  limit 5 " % (_type,_type,_type,sn,_type) )  
            result = c.fetchall()
            stable = ""
            if result == None:
                stable += "<a per='%s' onclick=\"changehuoyuebox('%s','%s','%s','%s','%s')\" href=\"javascript:;\">%s(%s)</a><br />" % (startdate,_pingtai,_type,'Start',startdate,cnsort.huoyuez(startdate),cnsort.huoyuez(startdate),startdate)
            else:
                for x in result:
                    stable += "<a per='%s' onclick=\"changehuoyuebox('%s','%s','%s','%s','%s')\" href=\"javascript:;\">%s(%s)</a><br />" % (x[0],_pingtai,_type,'Start',x[0],cnsort.huoyuez(x[0]),cnsort.huoyuez(x[0]),x[0])
        
        
        fanhui={}
        fanhui['sdate'] = cnsort.huoyuez(startdate)
        fanhui['edate'] = cnsort.huoyuez(enddate)
        fanhui['sper'] = startdate
        fanhui['eper'] = enddate
        fanhui['etable'] = etable
        fanhui['stable'] = stable
        
        
        c.close()
        db.close()
        self.write(fanhui)
        self.finish()
        

class ChangeBox(BaseHandler):
    def get(self):
        _type = self.get_argument('type','week').strip()
        _fx = self.get_argument('fx','<').strip()
        _zhi = self.get_argument('zhi','').strip()
        _shun = self.get_argument('shun','').strip()
        _pingtai = self.get_argument('pingtai','').strip()
        
        db = connectMySQL.connMySQL_stat()
        c=db.cursor()
        
        if _type == "week":
            
            sql = " select %s_number from `stat_activeUser_%s` where %s_period = '%s' limit 1 " % (_type,_type,_type,_zhi)
            c.execute(sql)  
            result = c.fetchone()
            zhi = result[0]
            
            if _fx == ">":
                _order = " asc  "
            else:
                _order = " desc "
                         
            sql = " select %s_number,%s_period from `stat_activeUser_%s` where %s_number %s %s order by %s_number %s limit 1 " % (_type,_type,_type,_type,_fx,zhi,_type,_order)
            
            #print sql
   
            c.execute(sql)  
            result = c.fetchone()
            zhic = result[1]
            
            zhic_list = zhic.split("-")
            zhic_str = zhic_list[0] 
            yy = zhic_str[0:4]
            mm = zhic_str[4:6]
            zhicc = "%s%s" % (yy,mm)
            
            
            sql = " select distinct(%s_period) from `stat_activeUser_%s` where %s_period like '%s%%'  order by %s_number asc " % (_type,_type,_type,zhicc,_type)
            c.execute(sql)  
            result = c.fetchall()
            table = ""
            for x in result:
                table += "<a per='%s' onclick=\"changehuoyuebox('%s','%s','%s','%s','%s')\" href=\"javascript:;\">%s(%s)</a><br />" % (x[0],_pingtai,_type,_shun,x[0],cnsort.huoyuez(x[0]),cnsort.huoyuez(x[0]),x[0])

        
        else:
        
            sql = " select %s_number from `stat_activeUser_%s` where %s_period = '%s' limit 1 " % (_type,_type,_type,_zhi)
            c.execute(sql)  
            result = c.fetchone()
            zhi = result[0]
            
            sql = " select distinct(%s_period) from `stat_activeUser_%s` where %s_number %s %s order by %s_number asc  limit 5 " % (_type,_type,_type,_fx,zhi,_type)
            c.execute(sql)  
            result = c.fetchall()
            table = ""
            for x in result:
                table += "<a per='%s' onclick=\"changehuoyuebox('%s','%s','%s','%s','%s')\" href=\"javascript:;\">%s(%s)</a><br />" % (x[0],_pingtai,_type,_shun,x[0],cnsort.huoyuez(x[0]),cnsort.huoyuez(x[0]),x[0])
        
        
        fanhui={}
        fanhui['table'] = table
        
        
        c.close()
        db.close()
        self.write(fanhui)
        self.finish()
        
        
class CloseTime(BaseHandler):
    def get(self):
        _type = self.get_argument('type','week').strip()
        _zhi = self.get_argument('zhi','-28').strip()
        _zhi = int(_zhi)
        _pingtai = self.get_argument('pingtai','').strip()
        
        db = connectMySQL.connMySQL_stat()
        c=db.cursor()
        fanhui={}
        fanhui['status'] = 1
        if _type == "week":
            a = datetime.datetime.today()
            ayear = a.strftime('%Y')
            en = "%s%s" % (ayear,str(datetime.datetime.isocalendar(a)[1]))
            b = a + datetime.timedelta(_zhi)
            byear = b.strftime('%Y')
            sn = "%s%s" % (byear,str(datetime.datetime.isocalendar(b)[1]))
            #print sn,en
            sql = " select %s_period from `stat_activeUser_%s` where %s_number >= '%s' order by %s_number asc  limit 1 " % (_type,_type,_type,sn,_type)
            print sql
            c.execute(sql)  
            result = c.fetchone()
            if result == None:
                fanhui['status'] = 0
            else:
                fanhui['stime'] = result[0]
                fanhui['sper'] = cnsort.huoyuez(result[0])
                sql = " select %s_period from `stat_activeUser_%s` where %s_number <= '%s' order by %s_number desc limit 1 " % (_type,_type,_type,en,_type)
                #print sql
                c.execute(sql)  
                result = c.fetchone()
                fanhui['etime'] = result[0]
                fanhui['eper'] = cnsort.huoyuez(result[0])
        else:
            a = datetime.datetime.today()
            ayear = a.strftime('%Y')
            en = "%s%s" % (ayear,a.strftime('%m'))
            b = a + datetime.timedelta(_zhi)
            byear = b.strftime('%Y')
            sn = "%s%s" % (byear,b.strftime('%m'))
            #print sn,en
            sql = " select %s_period from `stat_activeUser_%s` where %s_number >= '%s' order by %s_number asc limit 1 " % (_type,_type,_type,sn,_type)
            c.execute(sql)
            print sql
            result = c.fetchone()
            if result == None:
                fanhui['status'] = 0
            else:
                
                fanhui['stime'] = result[0]
                fanhui['sper'] = cnsort.huoyuez(result[0])
                c.execute(" select %s_period from `stat_activeUser_%s` where %s_number <= '%s' order by %s_number desc limit 1 " % (_type,_type,_type,en,_type))  
                result = c.fetchone()
                fanhui['etime'] = result[0]
                fanhui['eper'] = cnsort.huoyuez(result[0])
        
        c.close()
        db.close()
        self.write(fanhui)
        self.finish()



class CityDayVideo(BaseHandler):
    def get(self): 
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        
        
        try:
            st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
        except :
            self.send_error(400, desc='invalid argument')
            return
        
        if not _pd:
            ed_time = datetime.datetime.now()
            delta = ed_time - st_time 
            _pd =  abs(delta.days)
        
        _pd = int(_pd)
        et_time = st_time + datetime.timedelta(days=_pd)
        
        st_datestr = st_time.strftime('%Y%m%d')
        et_datestr = et_time.strftime('%Y%m%d')
        ex_time = et_time + datetime.timedelta(-1)
        ex_datestr = ex_time.strftime('%Y%m%d')
        
        
        #print et_datestr
        all_data = []
        results = {}
        os_data = []
        
        _osidsql = ""
        _device_typesql = ""
        
        if _osid != "":
            _osidsql = " and a.os_id in (%s) " % _osid
        
        if _device_type != "":
            _device_typesql = " and a.device_type in (%s) " % _device_type  
            
        if _osid == "" and _device_type == "":
             _osidsql = " and a.os_id in (61,59,52) "
             _device_typesql = " and a.device_type in (1,2) "
        
        db = connectMySQL.connMySQL_stat()
        c=db.cursor()
        
        fanhui = {}
        
        nowmonth = time.strftime('%m',time.localtime(time.time()))

        cc = int(nowmonth)
        cf = []
        start_time = datetime.datetime.now()
        for i in xrange(cc,12):
            ch={}
            ch['year'] = 2011
            if len(str(i)) == 1:
                i = "%s%s" % ("0",str(i))
            ch['month'] = i
            cf.append(ch)
        end_time = datetime.datetime.now()
        print u"1 time:%s" % (end_time-start_time)
        
        start_time = datetime.datetime.now()
        for i in xrange(1,cc+1):
            ch={}
            ch['year'] = 2012
            if len(str(i)) == 1:
                i = "%s%s" % ("0",str(i))
            ch['month'] = i
            cf.append(ch)
        end_time = datetime.datetime.now()
        print u"2 time:%s" % (end_time-start_time)
        chh = []
        start_time = datetime.datetime.now()
        for i in cf[::-1]:
            chh.append(i)
        end_time = datetime.datetime.now()
        print u"3 time:%s" % (end_time-start_time)
        cf = chh
        ghenglie = ""
        start_time = datetime.datetime.now()
        for cfv in cf:
            ghenglie += u"<th>%s/%s</th>" % (cfv['year'],cfv['month'])
        end_time = datetime.datetime.now()
        print u"4 time:%s" % (end_time-start_time)
        
        
        
        
            
        #省市概览表头
        g_prov_table = "<div class=\"csv-box-header\"><strong>省市占比年度概览</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydayvideoTableX1');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydayvideoTableX1');\" >下载</a></span><a href=\"javascript:getCSVData('channeldayTableX1');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>"
        
        g_prov_table += u"<div style='overflow:auto;height:200px;'><table class='new_silver_table' id='citydayvideoTableX1'  ><thead><tr><th onclick=\" tableSortingly('citydayvideoTableX1', 1,1); \"  id='citydayvideoTableX1th1' >序号</th><th>省市</th>"
        
        #城市概览表头
        g_city_table = "<div class=\"csv-box-header\"><strong>城市占比年度概览</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydayvideoTableX2');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydayvideoTableX2');\" >下载</a></span><a href=\"javascript:getCSVData('channeldayTableX2');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>"
        
        g_city_table += u"<div style='overflow:auto;height:200px;'><table class='new_silver_table' id='citydayvideoTableX2'  ><thead><tr><th onclick=\" tableSortingly('citydayvideoTableX2', 1,1); \"  id='citydayvideoTableX2th1' >序号</th><th>城市</th>"
        
        
        #省市明细表头
        m_prov_table = "<div class=\"csv-box-header\"><strong>省市明细(%s-%s)</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydayvideoTableX3');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydayvideoTableX3');\" >下载</a></span><a href=\"javascript:getCSVData('channeldayTableX3');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>" % (cnsort.fordate(st_datestr,1),cnsort.fordate(ex_datestr,1))
        
        m_prov_table += u"<div style='overflow:auto;height:200px;'><table class='new_silver_table' id='citydayvideoTableX3'  ><thead><tr><th onclick=\" tableSortingly('citydayvideoTableX3', 1,1); \"  id='citydayvideoTableX3th1' >序号</th><th>省市</th><th>访问次数</th><th>占比</th>"
        
        #城市明细表头
        m_city_table = "<div class=\"csv-box-header\"><strong>城市明细(%s-%s)</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydayvideoTableX4');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydayvideoTableX4');\" >下载</a></span><a href=\"javascript:getCSVData('channeldayTableX4');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>" % (cnsort.fordate(st_datestr,1),cnsort.fordate(ex_datestr,1))
        
        m_city_table += u"<div style='overflow:auto;height:200px;'><table class='new_silver_table' id='citydayvideoTableX4'  ><thead><tr><th onclick=\" tableSortingly('citydayvideoTableX4', 1,1); \"  id='citydayvideoTableX4th1' >序号</th><th>城市</th><th>访问次数</th><th>占比</th>"
        
        #省市明细表开始
        sql_prov = "SELECT sum(a.uv),b.prov_cn FROM `stat_day_total` a left join `stat_city_dict` b on a.prov = b.cprov_id  where a.date >= '%s' and a.date < '%s' and  a.business_type = 2 and a.pid_stat = 1  %s   %s and a.partner_mode in (1,2,3,8) group by b.prov_cn order by sum(a.uv) desc " % (st_datestr,et_datestr,_osidsql,_device_typesql)
        
        keyprovlist = []
        mshengzong = []
        print sql_prov
        c.execute(sql_prov)  
        result_prov = c.fetchall()
        start_time = datetime.datetime.now()                    
        for vv in result_prov:
            keyprovlist.append([vv[0],vv[1]])
            mshengzong.append(vv[0])
        end_time = datetime.datetime.now()
        print u"5 time:%s" % (end_time-start_time)
        jishu = 1
        bingtuprovx="["
        bingtuprovy="["
        length_p = len(keyprovlist)
        start_time = datetime.datetime.now()
        for i in xrange(length_p):
            bg = ""
            if jishu % 2 == 0:
                bg = " class='new_silver_even' "
            else:
                bg = " class='new_silver_odd' "
                
            xian = keyprovlist[i][0]
            zong = sum(mshengzong)
            try:    
                a = xian/zong
            except:
                a = 0
            zhanbi = round(a,4)*100
            
            m_prov_table += "<tr %s><td>%s</td><td>%s</td><td>%s</td><td>%s%%</td></tr>" % (bg,jishu,keyprovlist[i][1],cnsort.num2money(xian),zhanbi)
            
            if jishu <= 10:
                bingtuprovx += "'%s'," % keyprovlist[i][1]
                bingtuprovy += "%s," % keyprovlist[i][0]
            jishu = jishu + 1
        end_time = datetime.datetime.now()
        print u"6 time:%s" % (end_time-start_time)
        bingtuprovx += "]"
        bingtuprovy += "]"
        m_prov_table += "</table></div>"
        
        
        
        #城市明细表开始
        sql_city = "SELECT sum(a.uv),b.city_cn FROM `stat_day_total` a left join `stat_city_dict` b on a.city = b.ccity_id  where a.date >= '%s' and a.date < '%s' and  a.business_type = 2 and a.pid_stat = 1  %s   %s and a.partner_mode in (1,2,3,8) group by b.city_cn order by sum(a.uv) desc " % (st_datestr,et_datestr,_osidsql,_device_typesql)
        
        keycitylist = []
        mshengzong = []
        print sql_city
        c.execute(sql_city)  
        result_city = c.fetchall()
        start_time = datetime.datetime.now()                    
        for vv in result_city:
            keycitylist.append([vv[0],vv[1]])
            mshengzong.append(vv[0])
        
        end_time = datetime.datetime.now()
        print u"7 time:%s" % (end_time-start_time)
        jishu = 1
        bingtucityx="["
        bingtucityy="["
        length_l = len(keycitylist)
        start_time = datetime.datetime.now()
        for i in xrange(length_l):
            bg = ""
            if jishu % 2 == 0:
                bg = " class='new_silver_even' "
            else:
                bg = " class='new_silver_odd' "
                
            xian = keycitylist[i][0]
            zong = sum(mshengzong)
            try:    
                a = xian/zong
            except:
                a = 0
            zhanbi = round(a,4)*100
            
            m_city_table += "<tr %s><td>%s</td><td>%s</td><td>%s</td><td>%s%%</td></tr>" % (bg,jishu,keycitylist[i][1],cnsort.num2money(xian),zhanbi)
            
            if jishu <= 10:
                bingtucityx += "'%s'," % keycitylist[i][1]
                bingtucityy += "%s," % keycitylist[i][0]
            
            
            jishu = jishu + 1
        end_time = datetime.datetime.now()
        print u"8 time:%s" % (end_time-start_time)
        bingtucityx += "]"
        bingtucityy += "]"
        m_city_table += "</table></div>"
        
        m_table = "%s%s" % (m_prov_table,m_city_table)
        
        #省市概览表开始
        g_prov_table += ghenglie
        
        """
        startbdate = "%s%s01" % (cf[0]['year'],cf[0]['month'])
        zuihouyitian = calendar.monthrange(cf[11]['year'],int(cf[11]['month']))
        endbdate = "%s%s%s" % (cf[11]['year'],cf[11]['month'],zuihouyitian[1])
        
        
        sql = "SELECT sum(uv),b.prov_cn,b.city_cn,date FROM `stat_day_total` a left join `stat_city_dict` b on a.prov = b.cprov_id and a.city = b.ccity_id  WHERE a.date <= '%s' and a.date >= '%s' and  a.business_type = 2 and a.pid_stat = 1  %s  %s  and partner_mode in (1,2,3,8)  group by a.prov,a.city,a.date " % (startbdate,endbdate,_osidsql,_device_typesql)
        
        print sql
        c.execute(sql)  
        bresult = c.fetchall()
        
        kpl = []
        for i in xrange(len(keyprovlist)):
            hangzong = []
            ck2 = []
            for j in xrange(len(cf)):
                sk = []
                dk = []
                for jjj in bresult:
                    ccdd = str(jjj[3])
                    p1 = "%s%s" % (cf[j]['year'],cf[j]['month'])
                    if jjj[1] == keyprovlist[i][1] and ccdd.find(p1) != -1:
                        sk.append(int(jjj[0]))
                        dk.append(int(jjj[0]))
                    else:
                        sk.append(0)
                        dk.append(0)
                hangzong.append(sum(sk))
                ck2.append(sum(dk))
            kpl.append({'zongshu':sum(hangzong),'shulist':ck2})    
        
        
        
        jishu = 1
        for i in xrange(len(kpl)):
            bg = ""
            if jishu % 2 == 0:
                bg = " class='new_silver_even' "
            else:
                bg = " class='new_silver_odd' "
            g_prov_table += "<tr %s><td>%s</td><td>%s</td>" % (bg,jishu,keyprovlist[i][1])
            
                
            for j in xrange(len(kpl[i]['shulist'])):
                xian = kpl[i]['shulist'][j]
                shang = kpl[i-1]['shulist'][j]
                zong = kpl[i]['zongshu']
                
                try:    
                    a = xian/zong
                except:
                    a = 0
                zhanbi = round(a,4)*100
                
                cha = xian - shang
                    
                if cha > 0:
                    jiantou = "<span class='inc_tag' style='margin-left: 5px;' title='0%'><b> ↑ </b></span>"
                elif cha < 0:
                    jiantou = "<span class='des_tag' style='margin-left: 5px;' title='0%'><b> ↓ </b></span>"
                else:
                    jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
                    
                if i == 0:
                    jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
                
                
                g_prov_table += "<td>%s%%</td>" % (zhanbi) 
            
            g_prov_table += "</tr>"
            jishu = jishu + 1
        
        g_prov_table +="</table></div>"
        
        """
        
        #城市概览表开始
        """
        g_city_table += ghenglie
        
        
        
        kpl = []
        for i in xrange(len(keycitylist)):
            hangzong = []
            ck2 = []
            for j in xrange(len(cf)):
                sk = []
                dk = []
                for jjj in bresult:
                    ccdd = str(jjj[3])
                    p1 = "%s%s" % (cf[j]['year'],cf[j]['month'])
                    if jjj[2] == keycitylist[i][1] and ccdd.find(p1) != -1:
                        sk.append(int(jjj[0]))
                        dk.append(int(jjj[0]))
                    else:
                        sk.append(0)
                        dk.append(0)
                hangzong.append(sum(sk))
                ck2.append(sum(dk))
            kpl.append({'zongshu':sum(hangzong),'shulist':ck2})    
        
        
        
        jishu = 1
        for i in xrange(len(kpl)):
            bg = ""
            if jishu % 2 == 0:
                bg = " class='new_silver_even' "
            else:
                bg = " class='new_silver_odd' "
            g_city_table += "<tr %s><td>%s</td><td>%s</td>" % (bg,jishu,keycitylist[i][1])
            
                
            for j in xrange(len(kpl[i]['shulist'])):
                xian = kpl[i]['shulist'][j]
                shang = kpl[i-1]['shulist'][j]
                zong = kpl[i]['zongshu']
                
                try:    
                    a = xian/zong
                except:
                    a = 0
                zhanbi = round(a,4)*100
                
                cha = xian - shang
                    
                if cha > 0:
                    jiantou = "<span class='inc_tag' style='margin-left: 5px;' title='0%'><b> ↑ </b></span>"
                elif cha < 0:
                    jiantou = "<span class='des_tag' style='margin-left: 5px;' title='0%'><b> ↓ </b></span>"
                else:
                    jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
                    
                if i == 0:
                    jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
                
                
                g_city_table += "<td>%s%%</td>" % (zhanbi) 
            
            g_city_table += "</tr>"
            jishu = jishu + 1
        
        g_city_table +="</table></div>"
        """
        g_table = "%s%s" % (g_prov_table,g_city_table)
        
        fv = {}
        
        fv['mtable'] = m_table
        fv['gtable'] = g_table
        fv['bingtuprovx'] = bingtuprovx
        fv['bingtuprovy'] = bingtuprovy
        fv['bingtucityx'] = bingtucityx
        fv['bingtucityy'] = bingtucityy
        
        fanhui['All'] = fv
            
            
        
        c.close()
        db.close()
        self.write(fanhui)
        self.finish()

class CityDayVideo_123(BaseHandler):
    def get(self): 
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        
        _order = " "
        _whereos = " os_id in (61,59,52) "
        _wheredy = "  "
        
        if _osid != "":
            _whereos = " os_id = %s " % _osid
        
        if _device_type != "":
            _wheredy = " and device_type in (%s) " % _device_type
        
        try:
            st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
        except :
            self.send_error(400, desc='invalid argument')
            return
        
        if not _pd:
            ed_time = datetime.datetime.now()
            delta = ed_time - st_time 
            _pd =  abs(delta.days)
        
        _pd = int(_pd)
        et_time = st_time + datetime.timedelta(days=_pd)
        
        st_datestr = st_time.strftime('%Y%m%d')
        et_datestr = et_time.strftime('%Y%m%d')
        ex_time = et_time + datetime.timedelta(-1)
        ex_datestr = ex_time.strftime('%Y%m%d')
        
        
        #print et_datestr
        all_data = []
        results = {}
        os_data = []
        
        days = []
        days_l = []
        
        for i in xrange(0,_pd):
            now = datetime.datetime.strptime(st_datestr,'%Y%m%d') 
            delta = datetime.timedelta(days=i)  
            n_days = now + delta  
            days.append(n_days.strftime('%Y%m%d'))
            days_l.append({'days':n_days.strftime('%Y%m%d')})
        
        if _osid == "":
            xunhuan = [{'name':'All','id':'61,59,52','cc':[61,59,52]},{'name':'Android','id':'61','cc':[61]},{'name':'iOS','id':'52','cc':[52]},{'name':'WP7','id':'59','cc':[59]}]
        elif _device_type == "":
            xunhuan = [{'name':'All','id':'1,2','cc':[1,2]},{'name':'Phone','id':'1','cc':[1]},{'name':'Pad','id':'2','cc':[2]}]
        else:
            xunhuan = [{'name':'All'}]
        
        db = connectMySQL.connMySQL_stat()
        c=db.cursor()
        
        fanhui = {}
        
        
        nowmonth = time.strftime('%m',time.localtime(time.time()))

        cc = int(nowmonth)
        cf = []
        for i in xrange(cc,12):
            ch={}
            ch['year'] = 2011
            if len(str(i)) == 1:
                i = "%s%s" % ("0",str(i))
            ch['month'] = i
            cf.append(ch)
    
        for i in xrange(1,cc+1):
            ch={}
            ch['year'] = 2012
            if len(str(i)) == 1:
                i = "%s%s" % ("0",str(i))
            ch['month'] = i
            cf.append(ch)
        
        #chh = []
        #for i in cf[::-1]:
        #    chh.append(i)
        #cf = chh
        ghenglie = ""
        for cfv in cf:
            ghenglie += u"<th>%s/%s</th>" % (cfv['year'],cfv['month'])
            
        
        if _osid == "":
            if _osid == "" and _device_type == "":
                sql = " SELECT sum(a.uv),a.os_id,a.device_type,b.prov_cn,b.city_cn FROM `stat_day_total` a left join `stat_city_dict` b on a.prov = b.cprov_id and a.city = b.ccity_id  WHERE a.date >= '%s' and a.date < '%s' and  a.business_type = 2 and a.pid_stat = 1 and a.os_id in (61,59,52) and a.device_type in (1,2) and a.partner_mode in (1,2,3,8) group by a.prov,a.city,a.os_id " % (st_datestr,et_datestr)
            else:
                sql = " SELECT sum(a.uv),a.os_id,a.device_type,b.prov_cn,b.city_cn FROM `stat_day_total` a left join `stat_city_dict` b on a.prov = b.cprov_id and a.city = b.ccity_id WHERE a.date >= '%s' and a.date < '%s' and  a.business_type = 2 and a.pid_stat = 1 and a.os_id in (61,59,52) and a.device_type in (%s) and a.partner_mode in (1,2,3,8) group by prov,city,os_id " % (st_datestr,et_datestr,_device_type)
        elif _device_type == "":
            sql = "SELECT sum(a.uv),a.os_id,a.device_type,b.prov_cn,b.city_cn FROM `stat_day_total` a left join `stat_city_dict` b on a.prov = b.cprov_id and a.city = b.ccity_id WHERE a.date >= '%s' and a.date < '%s'  and  a.business_type = 2 and a.pid_stat = 1 and a.os_id in (%s) and a.device_type in (1,2) and a.partner_mode in (1,2,3,8) group by a.prov,a.city,a.device_type " % (st_datestr,et_datestr,_osid)
        else:
            sql = "SELECT sum(a.uv),a.os_id,a.device_type,b.prov_cn,b.city_cn FROM `stat_day_total` a left join `stat_city_dict` b on a.prov = b.cprov_id and a.city = b.ccity_id where a.date >= '%s' and a.date < '%s' and  a.business_type = 2 and a.pid_stat = 1 and a.os_id in (%s) and a.device_type in (%s) and a.partner_mode in (1,2,3,8) group by a.prov,a.city " % (st_datestr,et_datestr,_osid,_device_type)
        
        print sql
        c.execute(sql)  
        zong_result = c.fetchall()
        te_prov_list = []
        te_city_list = []
        for zzz in zong_result:
            if zzz[3] != None:
                sheng = zzz[3]
                te_prov_list.append("%s" % (sheng))
            #else:
            #    sheng = u"未知"
            
            if zzz[4] != None:
                city = zzz[4]
                te_city_list.append("%s" % (city))
            #else:
            #    city = u"未知"
            
        te_prov_list = set(te_prov_list)
        te_city_list = set(te_city_list)
        #print te_city_list 
        
        for vxunhuan in xrange(len(xunhuan)):
            
            #省市概览表头
            g_prov_table = "<div class=\"csv-box-header\"><strong>省市占比年度概览</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydayvideoTableX1');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydayvideoTableX1');\" >下载</a></span><a href=\"javascript:getCSVData('channeldayTableX1');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>"
            
            g_prov_table += u"<div style='overflow:auto;height:200px;'><table class='new_silver_table' id='citydayvideoTableX1'  ><thead><tr><th onclick=\" tableSortingly('citydayvideoTableX1', 1,1); \"  id='citydayvideoTableX1th1' >序号</th><th>省市</th>"
            
            #城市概览表头
            g_city_table = "<div class=\"csv-box-header\"><strong>城市占比年度概览</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydayvideoTableX2');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydayvideoTableX2');\" >下载</a></span><a href=\"javascript:getCSVData('channeldayTableX2');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>"
            
            g_city_table += u"<div style='overflow:auto;height:200px;'><table class='new_silver_table' id='citydayvideoTableX2'  ><thead><tr><th onclick=\" tableSortingly('citydayvideoTableX2', 1,1); \"  id='citydayvideoTableX2th1' >序号</th><th>城市</th>"
            
            
            #省市明细表头
            m_prov_table = "<div class=\"csv-box-header\"><strong>省市明细(%s-%s)</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydayvideoTableX3');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydayvideoTableX3');\" >下载</a></span><a href=\"javascript:getCSVData('channeldayTableX3');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>" % (cnsort.fordate(st_datestr,1),cnsort.fordate(ex_datestr,1))
            
            m_prov_table += u"<div style='overflow:auto;height:200px;'><table class='new_silver_table' id='citydayvideoTableX3'  ><thead><tr><th onclick=\" tableSortingly('citydayvideoTableX3', 1,1); \"  id='citydayvideoTableX3th1' >序号</th><th>省市</th><th>访问次数</th><th>占比</th>"
            
            #城市明细表头
            m_city_table = "<div class=\"csv-box-header\"><strong>城市明细(%s-%s)</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydayvideoTableX4');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydayvideoTableX4');\" >下载</a></span><a href=\"javascript:getCSVData('channeldayTableX4');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>" % (cnsort.fordate(st_datestr,1),cnsort.fordate(ex_datestr,1))
            
            m_city_table += u"<div style='overflow:auto;height:200px;'><table class='new_silver_table' id='citydayvideoTableX4'  ><thead><tr><th onclick=\" tableSortingly('citydayvideoTableX4', 1,1); \"  id='citydayvideoTableX4th1' >序号</th><th>城市</th><th>访问次数</th><th>占比</th>"
            
            #省市明细表开始
            
            keylist = []
            mshengzong = []
            #print te_prov_list
            
            for vv in te_prov_list:
                he = []
                for te in zong_result:
                    if _osid == "":
                        if str(vv) == str(te[3]) and int(te[1]) in xunhuan[vxunhuan]['cc']:
                            he.append(te[0])
                    elif _device_type == "":
                        if str(vv) == str(te[3]) and int(te[2]) in xunhuan[vxunhuan]['cc']:
                            he.append(te[0])
                    else:
                        if str(vv) == str(te[3]):
                            he.append(te[0])
                keylist.append([sum(he),str(vv),str(vv)])
            jishu = 1
            keylist = sorted(keylist,reverse=True)
            keyprovlist = []
            
            for kk in keylist:
                keyprovlist.append([kk[0],kk[1],kk[2]])
                mshengzong.append(kk[0])           
            #print keyprovlist
            bingtuprovx="["
            bingtuprovy="["
            for i in xrange(len(keyprovlist)):
                bg = ""
                if jishu % 2 == 0:
                    bg = " class='new_silver_even' "
                else:
                    bg = " class='new_silver_odd' "
                    
                xian = keyprovlist[i][0]
                zong = sum(mshengzong)
                try:    
                    a = xian/zong
                except:
                    a = 0
                zhanbi = round(a,4)*100
                
                m_prov_table += "<tr %s><td>%s</td><td>%s</td><td>%s</td><td>%s%%</td></tr>" % (bg,jishu,keyprovlist[i][1],cnsort.num2money(xian),zhanbi)
                
                if jishu <= 10:
                    bingtuprovx += "'%s'," % keyprovlist[i][1]
                    bingtuprovy += "%s," % keyprovlist[i][0]
                
                
                jishu = jishu + 1
            
            bingtuprovx += "]"
            bingtuprovy += "]"
            m_prov_table += "</table></div>"
            
            
            #print bingtuprovy
            
            
            #城市明细表开始
            keylist = []
            mshengzong = []
            #print te_city_list
            
            for vv in te_city_list:
                he = []
                for te in zong_result:
                    #_stimelist = vv.split("+")
                    if _osid == "":
                        if str(vv) == str(te[4]) and int(te[1]) in xunhuan[vxunhuan]['cc']:
                            he.append(te[0])
                    elif _device_type == "":
                        if str(vv) == str(te[4]) and int(te[2]) in xunhuan[vxunhuan]['cc']:
                            he.append(te[0])
                    else:
                        if str(vv) == str(te[4]):
                            he.append(te[0])
                keylist.append([sum(he),str(vv),str(vv)])
            jishu = 1
            keylist = sorted(keylist,reverse=True)
            keycitylist = []
            
            for kk in keylist:
                keycitylist.append([kk[0],kk[1],kk[2]])
                mshengzong.append(kk[0])           
            #print keycitylist
            bingtucityx="["
            bingtucityy="["
            for i in xrange(len(keycitylist)):
                bg = ""
                if jishu % 2 == 0:
                    bg = " class='new_silver_even' "
                else:
                    bg = " class='new_silver_odd' "
                    
                xian = keycitylist[i][0]
                zong = sum(mshengzong)
                try:    
                    a = xian/zong
                except:
                    a = 0
                zhanbi = round(a,4)*100
                
                m_city_table += "<tr %s><td>%s</td><td>%s</td><td>%s</td><td>%s%%</td></tr>" % (bg,jishu,keycitylist[i][1],cnsort.num2money(xian),zhanbi)
                
                if jishu <= 10:
                    bingtucityx += "'%s'," % keycitylist[i][1]
                    bingtucityy += "%s," % keycitylist[i][0]
                
                
                jishu = jishu + 1
            
            bingtucityx += "]"
            bingtucityy += "]"
            m_city_table += "</table></div>"
            
            #print m_city_table
            
            m_table = "%s%s" % (m_prov_table,m_city_table)
            
            #省市概览表开始
            g_prov_table += ghenglie
            """
            
            startbdate = "%s%s01" % (cf[0]['year'],cf[0]['month'])
            zuihouyitian = calendar.monthrange(cf[11]['year'],int(cf[11]['month']))
            endbdate = "%s%s%s" % (cf[11]['year'],cf[11]['month'],zuihouyitian[1])
            
            #print startbdate
            
            if _osid == "":
                if _osid == "" and _device_type == "":
                    sql = "SELECT sum(uv),prov,city,date FROM `stat_day_total` WHERE date <= '%s' and date >= '%s' and  business_type = 2 and pid_stat = 1 and os_id in (%s) and device_type in (1,2) and partner_mode in (1,2,3,8) group by prov,city,date  " % (startbdate,endbdate,xunhuan[vxunhuan]['id'])
                else:
                    sql = "SELECT sum(uv),prov,city,date FROM `stat_day_total` WHERE date <= '%s' and date >= '%s' and  business_type = 2 and pid_stat = 1 and os_id in (%s) and device_type in (%s) and partner_mode in (1,2,3,8) group by prov,city,date " % (startbdate,endbdate,xunhuan[vxunhuan]['id'],_device_type)
            elif _device_type == "":
                sql = "SELECT sum(uv),prov,city,date FROM `stat_day_total` WHERE date <= '%s' and date >= '%s'  and  business_type = 2 and pid_stat = 1 and os_id in (%s) and device_type in (%s) and partner_mode in (1,2,3,8)  group by prov,city,date " % (startbdate,endbdate,_osid,xunhuan[vxunhuan]['id'])
            else:
                sql = "SELECT sum(uv),prov,city,date FROM `stat_day_total` WHERE date <= '%s' and date >= '%s' and  business_type = 2 and pid_stat = 1 and os_id in (%s) and device_type in (%s) and partner_mode in (1,2,3,8)  group by prov,city,date " % (startbdate,endbdate,_osid,_device_type)
            #print sql
            c.execute(sql)  
            bresult = c.fetchall()
            
            #print sql
            
            
            kpl = []
            for i in xrange(len(keyprovlist)):
                hangzong = []
                ck2 = []
                for j in xrange(len(cf)):
                    sk = []
                    dk = []
                    for jjj in bresult:
                        ccdd = str(jjj[3])
                        p1 = "%s%s" % (cf[j]['year'],cf[j]['month'])
                        if jjj[1] == keyprovlist[i][2] and ccdd.find(p1) != -1:
                            sk.append(int(jjj[0]))
                            dk.append(int(jjj[0]))
                        else:
                            sk.append(0)
                            dk.append(0)
                    hangzong.append(sum(sk))
                    ck2.append(sum(dk))
                kpl.append({'zongshu':sum(hangzong),'shulist':ck2})    
            
            
            
            jishu = 1
            for i in xrange(len(kpl)):
                bg = ""
                if jishu % 2 == 0:
                    bg = " class='new_silver_even' "
                else:
                    bg = " class='new_silver_odd' "
                g_prov_table += "<tr %s><td>%s</td><td>%s</td>" % (bg,jishu,keyprovlist[i][1])
                
                    
                for j in xrange(len(kpl[i]['shulist'])):
                    xian = kpl[i]['shulist'][j]
                    shang = kpl[i-1]['shulist'][j]
                    zong = kpl[i]['zongshu']
                    
                    try:    
                        a = xian/zong
                    except:
                        a = 0
                    zhanbi = round(a,4)*100
                    
                    cha = xian - shang
                        
                    if cha > 0:
                        jiantou = "<span class='inc_tag' style='margin-left: 5px;' title='0%'><b> ↑ </b></span>"
                    elif cha < 0:
                        jiantou = "<span class='des_tag' style='margin-left: 5px;' title='0%'><b> ↓ </b></span>"
                    else:
                        jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
                        
                    if i == 0:
                        jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
                    
                    
                    g_prov_table += "<td>%s%%</td>" % (zhanbi) 
                
                g_prov_table += "</tr>"
                jishu = jishu + 1
            
            g_prov_table +="</table></div>"
            """
            
            #城市概览表开始
            
            g_city_table += ghenglie
            """
            
            
            kpl = []
            for i in xrange(len(keycitylist)):
                hangzong = []
                ck2 = []
                for j in xrange(len(cf)):
                    sk = []
                    dk = []
                    for jjj in bresult:
                        ccdd = str(jjj[3])
                        p1 = "%s%s" % (cf[j]['year'],cf[j]['month'])
                        if jjj[2] == keycitylist[i][2] and ccdd.find(p1) != -1:
                            sk.append(int(jjj[0]))
                            dk.append(int(jjj[0]))
                        else:
                            sk.append(0)
                            dk.append(0)
                    hangzong.append(sum(sk))
                    ck2.append(sum(dk))
                kpl.append({'zongshu':sum(hangzong),'shulist':ck2})    
            
            
            
            jishu = 1
            for i in xrange(len(kpl)):
                bg = ""
                if jishu % 2 == 0:
                    bg = " class='new_silver_even' "
                else:
                    bg = " class='new_silver_odd' "
                g_city_table += "<tr %s><td>%s</td><td>%s</td>" % (bg,jishu,keycitylist[i][1])
                
                    
                for j in xrange(len(kpl[i]['shulist'])):
                    xian = kpl[i]['shulist'][j]
                    shang = kpl[i-1]['shulist'][j]
                    zong = kpl[i]['zongshu']
                    
                    try:    
                        a = xian/zong
                    except:
                        a = 0
                    zhanbi = round(a,4)*100
                    
                    cha = xian - shang
                        
                    if cha > 0:
                        jiantou = "<span class='inc_tag' style='margin-left: 5px;' title='0%'><b> ↑ </b></span>"
                    elif cha < 0:
                        jiantou = "<span class='des_tag' style='margin-left: 5px;' title='0%'><b> ↓ </b></span>"
                    else:
                        jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
                        
                    if i == 0:
                        jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
                    
                    
                    g_city_table += "<td>%s%%</td>" % (zhanbi) 
                
                g_city_table += "</tr>"
                jishu = jishu + 1
            
            g_city_table +="</table></div>"
            
            g_table = "%s%s" % (g_prov_table,g_city_table)
            """
            fv = {}
            
            fv['mtable'] = m_table
            fv['gtable'] = '123'
            fv['bingtuprovx'] = bingtuprovx
            fv['bingtuprovy'] = bingtuprovy
            fv['bingtucityx'] = bingtucityx
            fv['bingtucityy'] = bingtucityy

            
            fanhui[xunhuan[vxunhuan]['name']] = fv
            
            
        
        c.close()
        db.close()
        self.write(fanhui)
        self.finish()



class CityDayVideo_copy(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        _limit = self.get_argument('limit','10').strip()
        
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        m_value = mc.get(_md5.hexdigest()) or {}
        #print m_value
        
        if settings.cache_on == 0:
            m_value = {}
        
        if not m_value:
        
            
            try:
                st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                return
            
            if not _pd:
                ed_time = datetime.datetime.now()
                delta = ed_time - st_time 
                _pd =  abs(delta.days)
            
            _pd = int(_pd)
            et_time = st_time + datetime.timedelta(days=_pd)
            
            st_datestr = st_time.strftime('%Y%m%d')
            et_datestr = et_time.strftime('%Y%m%d')
            ex_time = et_time + datetime.timedelta(-1)
            ex_datestr = ex_time.strftime('%Y%m%d')
            
            
            #print et_datestr
            all_data = []
            results = {}
            os_data = []
            
            
            if _osid == "":
                xunhuan = [{'name':'All','id':'-1'},{'name':'Android','id':'61'},{'name':'iOS','id':'52'},{'name':'WP7','id':'59'}]
            elif _device_type == "":
                xunhuan = [{'name':'All','id':'-1'},{'name':'Phone','id':'1'},{'name':'Pad','id':'2'}]
            else:
                xunhuan = [{'name':'All'}]
            
            db = connectMySQL.connMySQL_stat()
            c=db.cursor()
            
            fanhui = {}
            
            
            nowmonth = time.strftime('%m',time.localtime(time.time()))

            cc = int(nowmonth)
            cf = []
            for i in xrange(cc,12):
                ch={}
                ch['year'] = 2011
                if len(str(i)) == 1:
                    i = "%s%s" % ("0",str(i))
                ch['month'] = i
                cf.append(ch)
        
            for i in xrange(1,cc+1):
                ch={}
                ch['year'] = 2012
                if len(str(i)) == 1:
                    i = "%s%s" % ("0",str(i))
                ch['month'] = i
                cf.append(ch)
            
            chh = []
            for i in cf[::-1]:
                chh.append(i)
            cf = chh
            
            #print cf[11]
            ghenglie = ""
            for cfv in cf:
                ghenglie += u"<th>%s/%s</th>" % (cfv['year'],cfv['month'])
            
            
            
            for vxunhuan in xrange(len(xunhuan)):
                
                #省市概览表头
                g_prov_table = "<div class=\"csv-box-header\"><strong>省市占比年度概览</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydayvideoTableX1');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydayvideoTableX1');\" >下载</a></span><a href=\"javascript:getCSVData('citydayvideoTableX1');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>"
                
                g_prov_table += u"<div style='overflow:auto;height:200px;'><table class='new_silver_table' id='citydayvideoTableX1'  ><thead><tr><th onclick=\" tableSortingly('citydayvideoTableX1', 1,1); \"  id='citydayvideoTableX1th1' >序号</th><th>省市</th>"
                
                #城市概览表头
                g_city_table = "<div class=\"csv-box-header\"><strong>城市占比年度概览</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydayvideoTableX2');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydayvideoTableX2');\" >下载</a></span><a href=\"javascript:getCSVData('citydayvideoTableX2');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>"
                
                g_city_table += u"<div style='overflow:auto;height:200px;'><table class='new_silver_table' id='citydayvideoTableX2'  ><thead><tr><th onclick=\" tableSortingly('citydayvideoTableX2', 1,1); \"  id='citydayvideoTableX2th1' >序号</th><th>城市</th>"
                
                table_msg = ""
                
                #省市明细表头
                #m_prov_table = "<div class=\"csv-box-header\"><strong>省市明细(%s-%s)</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydayvideoTableX3');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydayvideoTableX3');\" >下载</a></span><a href=\"javascript:getCSVData('citydayvideoTableX3');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>" % (cnsort.fordate(st_datestr,1),cnsort.fordate(ex_datestr,1))
                m_prov_table = "<div class=\"csv-box-header\"><strong>省市明细%s</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydayvideoTableX3');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydayvideoTableX3');\" >下载</a></span><a href=\"javascript:getCSVData('citydayvideoTableX3');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>" % table_msg
                
                m_prov_table += u"<div style='overflow:auto;height:200px;'><table class='new_silver_table' id='citydayvideoTableX3'  ><thead><tr><th onclick=\" tableSortingly('citydayvideoTableX3', 1,1); \"  id='citydayvideoTableX3th1' >序号</th><th>省市</th><th>用户数(日UV累计)</th><th>占比</th>"
                
                #城市明细表头
                #m_city_table = "<div class=\"csv-box-header\"><strong>城市明细(%s-%s)</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydayvideoTableX4');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydayvideoTableX4');\" >下载</a></span><a href=\"javascript:getCSVData('citydayvideoTableX4');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>" % (cnsort.fordate(st_datestr,1),cnsort.fordate(ex_datestr,1))
                m_city_table = "<div class=\"csv-box-header\"><strong>城市明细%s</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydayvideoTableX4');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydayvideoTableX4');\" >下载</a></span><a href=\"javascript:getCSVData('citydayvideoTableX4');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>" % table_msg
                
                m_city_table += u"<div style='overflow:auto;height:200px;'><table class='new_silver_table' id='citydayvideoTableX4'  ><thead><tr><th onclick=\" tableSortingly('citydayvideoTableX4', 1,1); \"  id='citydayvideoTableX4th1' >序号</th><th>城市</th><th>用户数(日UV累计)</th><th>占比</th>"
                
                #省市明细表开始
                keylist = []
                mshengzong = []
                if _osid == "":
                    if _osid == "" and _device_type == "":
                        #sql = "SELECT sum(uv),prov FROM `result_total_area` WHERE date >= '%s' and date < '%s' and  os_id  = '%s' group by prov order by sum(uv) desc  " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'])
                        
                        sql = "select sumtoal,prov,sumtoal/(select sum(uv) as total from `result_total_area` where date >= %s and date <= %s  and  os_id  = %s) total from (SELECT sum(uv) sumtoal,prov FROM `result_total_area` WHERE date >= %s and date <= %s  and  os_id  = %s group by prov ) a order by sumtoal desc  " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],st_datestr,et_datestr,xunhuan[vxunhuan]['id'])
                        
                        
                    else:
                        #sql = "SELECT sum(uv),prov FROM `result_total_area` WHERE date >= '%s' and date < '%s' and  os_id = '%s' and device_type = '%s'  group by prov order by sum(uv) desc  " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type)
                        
                        sql = "select sumtoal,prov,sumtoal/(select sum(uv) as total from `result_total_area` where date >= %s and date <= %s  and  os_id  = %s and device_type = %s) total from (SELECT sum(uv) sumtoal,prov FROM `result_total_area` WHERE date >= %s and date <= %s  and  os_id  = %s and device_type = %s group by prov ) a order by sumtoal desc  " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type,st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type)
                        
                elif _device_type == "":
                    #sql = "SELECT sum(uv),prov FROM `result_total_area` WHERE date >= '%s' and date < '%s'  and  os_id = '%s' and device_type = '%s'  group by prov order by sum(uv) desc  " % (st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'])
                    
                    sql = "select sumtoal,prov,sumtoal/(select sum(uv) as total from `result_total_area` where date >= %s and date <= %s  and  os_id  = %s and device_type = %s) total from (SELECT sum(uv) sumtoal,prov FROM `result_total_area` WHERE date >= %s and date <= %s  and  os_id  = %s and device_type = %s group by prov ) a order by sumtoal desc  " % (st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'],st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'])
                else:
                    #sql = "SELECT sum(uv),prov FROM `result_total_area` WHERE date >= '%s' and date < '%s' and  os_id = '%s' and device_type = '%s'  group by prov order by sum(uv) desc  " % (st_datestr,et_datestr,_osid,_device_type)
                    
                    sql = "select sumtoal,prov,sumtoal/(select sum(uv) as total from `result_total_area` where date >= %s and date <= %s  and  os_id  = %s and device_type = %s) total from (SELECT sum(uv) sumtoal,prov FROM `result_total_area` WHERE date >= %s and date <= %s  and  os_id  = %s and device_type = %s group by prov ) a order by sumtoal desc  " % (st_datestr,et_datestr,_osid,_device_type,st_datestr,et_datestr,_osid,_device_type)
                    
                print sql
                c.execute(sql)  
                result = c.fetchall()
                keyprovlist = []                    
                #for vv in result:
                #    keyprovlist.append([vv[0],vv[1]])
                jishu = 1
                bingtuprovx="["
                bingtuprovy="["
                for i in result:
                    bg = ""
                    if jishu % 2 == 0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                        
                    xian = int(i[0])
                    zhanbi = round(float(i[2]),4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        m_prov_table += "<tr %s><td>%s</td><td>%s</td><td>%s</td><td>%s0%%</td></tr>" % (bg,jishu,str(i[1]),cnsort.num2money(xian),(zhanbi)*100)
                    else:
                        m_prov_table += "<tr %s><td>%s</td><td>%s</td><td>%s</td><td>%s%%</td></tr>" % (bg,jishu,str(i[1]),cnsort.num2money(xian),(zhanbi)*100)
                    
                    if jishu <= 10:
                        bingtuprovx += "'%s'," % str(i[1])
                        bingtuprovy += "%s," % int(i[0])
                    
                    jishu = jishu + 1
                
                bingtuprovx += "]"
                bingtuprovy += "]"
                m_prov_table += "</table></div>"
                
                
                #print bingtuprovy
                
                
                #城市明细表开始
                keylist = []
                mshengzong = []
                if _osid == "":
                    if _osid == "" and _device_type == "":
                        #sql = "SELECT sum(uv),city FROM `result_total_area` WHERE date >= '%s' and date < '%s' and  os_id  = '%s' group by city order by sum(uv) desc  " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'])
                        
                        sql = "select sumtoal,city,sumtoal/(select sum(uv) as total from `result_total_area` where date >= %s and date <= %s  and  os_id  = %s) total from (SELECT sum(uv) sumtoal,city FROM `result_total_area` WHERE date >= %s and date <= %s  and  os_id  = %s group by city ) a order by sumtoal desc  " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],st_datestr,et_datestr,xunhuan[vxunhuan]['id'])
                        
                    else:
                        #sql = "SELECT sum(uv),city FROM `result_total_area` WHERE date >= '%s' and date < '%s' and  os_id  = '%s' and device_type = '%s' group by city order by sum(uv) desc  " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type)
                        
                        sql = "select sumtoal,city,sumtoal/(select sum(uv) as total from `result_total_area` where date >= %s and date <= %s  and  os_id  = %s and device_type = %s) total from (SELECT sum(uv) sumtoal,city FROM `result_total_area` WHERE date >= %s and date <= %s  and  os_id  = %s and device_type = %s group by city ) a order by sumtoal desc  " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type,st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type)
                        
                        
                elif _device_type == "":
                    #sql = "SELECT sum(uv),city FROM `result_total_area` WHERE date >= '%s' and date < '%s' and  os_id  = '%s' and device_type = '%s' group by city order by sum(uv) desc  " % (st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'])
                    
                    sql = "select sumtoal,city,sumtoal/(select sum(uv) as total from `result_total_area` where date >= %s and date <= %s  and  os_id  = %s and device_type = %s) total from (SELECT sum(uv) sumtoal,city FROM `result_total_area` WHERE date >= %s and date <= %s  and  os_id  = %s and device_type = %s group by city ) a order by sumtoal desc  " % (st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'],st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'])
                    
                else:
                    #sql = "SELECT sum(uv),city FROM `result_total_area` WHERE date >= '%s' and date < '%s' and  os_id  = '%s' and device_type = '%s' group by city order by sum(uv) desc  " % (st_datestr,et_datestr,_osid,_device_type)
                    #sql = "SELECT sum(uv),city FROM `result_total_area` WHERE date >= '%s' and date < '%s' and  os_id  = '%s' and device_type = '%s' group by city order by sum(uv) desc  " % (st_datestr,et_datestr,_osid,_device_type)
                    
                    sql = "select sumtoal,city,sumtoal/(select sum(uv) as total from `result_total_area` where date >= %s and date <= %s  and  os_id  = %s and device_type = %s) total from (SELECT sum(uv) sumtoal,city FROM `result_total_area` WHERE date >= %s and date <= %s  and  os_id  = %s and device_type = %s group by city ) a order by sumtoal desc  " % (st_datestr,et_datestr,_osid,_device_type,st_datestr,et_datestr,_osid,_device_type)
                    
                c.execute(sql)  
                result = c.fetchall()
                #keycitylist = []                    
                #for vv in result:
                #    keycitylist.append([vv[0],vv[1]])
                #    mshengzong.append(vv[0])
                jishu = 1
                bingtucityx="["
                bingtucityy="["
                for i in result:
                    bg = ""
                    if jishu % 2 == 0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                        
                    xian = int(i[0])
                    zhanbi = round(float(i[2]),4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        m_city_table += "<tr %s><td>%s</td><td>%s</td><td>%s</td><td>%s0%%</td></tr>" % (bg,jishu,str(i[1]),cnsort.num2money(xian),(zhanbi)*100)
                    else:
                        m_city_table += "<tr %s><td>%s</td><td>%s</td><td>%s</td><td>%s%%</td></tr>" % (bg,jishu,str(i[1]),cnsort.num2money(xian),(zhanbi)*100)
                    
                    if jishu <= 10:
                        bingtucityx += "'%s'," % str(i[1])
                        bingtucityy += "%s," % int(i[0])
                    
                    jishu = jishu + 1
                
                bingtucityx += "]"
                bingtucityy += "]"
                m_city_table += "</table></div>"
                
                #print m_city_table
                
                m_table = "%s%s" % (m_prov_table,m_city_table)
                
                #省市概览表开始
                g_prov_table += ghenglie
                endbdate = "%s%s01" % (cf[11]['year'],cf[11]['month'])
                zuihouyitian = calendar.monthrange(cf[0]['year'],int(cf[0]['month']))
                startbdate = "%s%s%s" % (cf[0]['year'],cf[0]['month'],zuihouyitian[1])
                
                #print startbdate
                """
                if _osid == "":
                    if _osid == "" and _device_type == "":
                        sql = "SELECT sum(uv),prov,city,date FROM `result_total_area` WHERE date >= '%s' and date < '%s' and  os_id  = '%s' group by prov,city,date  " % (endbdate,startbdate,xunhuan[vxunhuan]['id'])
                    else:
                        sql = "SELECT sum(uv),prov,city,date FROM `result_total_area` WHERE date >= '%s' and date < '%s' and  os_id  = '%s' and device_type = '%s' group by prov,city,date " % (endbdate,startbdate,xunhuan[vxunhuan]['id'],_device_type)
                elif _device_type == "":
                    sql = "SELECT sum(uv),prov,city,date FROM `result_total_area` WHERE date >= '%s' and date < '%s' and  os_id  = '%s' and device_type = '%s' group by prov,city,date " % (endbdate,startbdate,_osid,xunhuan[vxunhuan]['id'])
                else:
                    sql = "SELECT sum(uv),prov,city,date FROM `result_total_area` WHERE date >= '%s' and date < '%s' and  os_id  = '%s' and device_type = '%s' group by prov,city,date " % (endbdate,startbdate,_osid,_device_type)
                c.execute(sql)  
                bresult = c.fetchall()
                
                
                kpl = []
                for i in xrange(len(keyprovlist)):
                    ck2 = []
                    for j in xrange(len(cf)):
                        dk = []
                        for jjj in bresult:
                            ccdd = str(jjj[3])
                            p1 = "%s%s" % (cf[j]['year'],cf[j]['month'])
                            if jjj[1] == keyprovlist[i][1] and ccdd.find(p1) != -1:
                                dk.append(int(jjj[0]))
                            else:
                                dk.append(0)
                        ck2.append(sum(dk))
                    kpl.append({'shulist':ck2})    
                
                
                #print kpl
                jishu = 1
                for i in xrange(len(kpl)):
                    bg = ""
                    if jishu % 2 == 0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                    g_prov_table += "<tr %s><td>%s</td><td>%s</td>" % (bg,jishu,keyprovlist[i][1])
                    
                        
                    for j in xrange(len(kpl[i]['shulist'])):
                        xian = kpl[i]['shulist'][j]
                        
                        zzong = 0
                        
                        for kc in xrange(len(kpl)):
                            zzong += int(kpl[kc]['shulist'][j])
                        
                        
                        try:    
                            a = xian/zong
                        except:
                            a = 0
                        zhanbi = round(a,4)
                        
                        nl = str(zhanbi).split(".")
                        if len(str(nl[1])) < 4:
                            g_prov_table += "<td>%s0%%</td>" % (zhanbi*100)
                        else:
                            g_prov_table += "<td>%s%%</td>" % (zhanbi*100) 
                    
                    g_prov_table += "</tr>"
                    jishu = jishu + 1
                
                g_prov_table +="</table></div>"
                
                
                #城市概览表开始
                
                g_city_table += ghenglie
                
                #print startbdate
                
                kpl = []
                for i in xrange(len(keycitylist)):
                    hangzong = []
                    ck2 = []
                    for j in xrange(len(cf)):
                        sk = []
                        dk = []
                        for jjj in bresult:
                            ccdd = str(jjj[3])
                            p1 = "%s%s" % (cf[j]['year'],cf[j]['month'])
                            if jjj[2] == keycitylist[i][1] and ccdd.find(p1) != -1:
                                sk.append(int(jjj[0]))
                                dk.append(int(jjj[0]))
                            else:
                                sk.append(0)
                                dk.append(0)
                        hangzong.append(sum(sk))
                        ck2.append(sum(dk))
                    kpl.append({'zongshu':sum(hangzong),'shulist':ck2})    
                
                
                
                jishu = 1
                for i in xrange(len(kpl)):
                    bg = ""
                    if jishu % 2 == 0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                    g_city_table += "<tr %s><td>%s</td><td>%s</td>" % (bg,jishu,keycitylist[i][1])
                    
                        
                    for j in xrange(len(kpl[i]['shulist'])):
                        xian = kpl[i]['shulist'][j]
               
                        zzong = []
                        
                        for kc in xrange(len(kpl)):
                            zzong.append(kpl[kc]['shulist'][j])
                        
                        zong = sum(zzong)
                        
                        try:    
                            a = xian/zong
                        except:
                            a = 0
                        zhanbi = round(a,4)
                        
                        
                        
                        nl = str(zhanbi).split(".")
                        if len(str(nl[1])) < 4:
                            g_city_table += "<td>%s0%%</td>" % (zhanbi*100)
                        else:
                            g_city_table += "<td>%s%%</td>" % (zhanbi*100) 
                    
                    g_city_table += "</tr>"
                    jishu = jishu + 1
                
                g_city_table +="</table></div>"
                
                g_table = "%s%s" % (g_prov_table,g_city_table)
                """
                
                
            
                
                if _osid == "":
                    if _osid == "" and _device_type == "":
                        sql = "select `table` from result_total_yeartable where startdate = '%s' and enddate = '%s'  and os_id = '%s' and device_type = '-1' " % (startbdate,endbdate,xunhuan[vxunhuan]['id'])
                    else:
                        sql = "select `table` from result_total_yeartable where startdate = '%s' and enddate = '%s'  and os_id = '%s' and device_type = '%s' " % (startbdate,endbdate,xunhuan[vxunhuan]['id'],_device_type)
                elif _device_type == "":
                    sql = "select `table` from result_total_yeartable where startdate = '%s' and enddate = '%s'  and os_id = '%s' and device_type = '%s' " % (startbdate,endbdate,_osid,xunhuan[vxunhuan]['id'])
                else:
                    sql = "select `table` from result_total_yeartable where startdate = '%s' and enddate = '%s'  and os_id = '%s' and device_type = '%s' " % (startbdate,endbdate,_osid,_device_type)
                
                print sql
                c.execute(sql)  
                oneresult = c.fetchone()
                
                if oneresult != None:
                    g_table = oneresult[0]
                else:
                    g_table = "%s%s" % (g_prov_table,g_city_table)
                
                
                fv = {}
                
                fv['mtable'] = m_table
                fv['gtable'] = g_table
                fv['bingtuprovx'] = bingtuprovx
                fv['bingtuprovy'] = bingtuprovy
                fv['bingtucityx'] = bingtucityx
                fv['bingtucityy'] = bingtucityy

                
                fanhui[xunhuan[vxunhuan]['name']] = fv
                
                
            
            c.close()
            db.close()
            _url = hashlib.md5(_url)
            _url.digest()
            try:
                mc.set(_url.hexdigest(),fanhui,1024*1024)
            except:
                pass
        else:
            fanhui = m_value
        self.write(fanhui)
        self.finish()


class CityDayVideo_copy_copy(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        m_value = mc.get(_md5.hexdigest()) or {}
        #print m_value
        
        if settings.cache_on == 0:
            m_value = {}
        
        if not m_value:
        
            
            try:
                st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                return
            
            if not _pd:
                ed_time = datetime.datetime.now()
                delta = ed_time - st_time 
                _pd =  abs(delta.days)
            
            _pd = int(_pd)
            et_time = st_time + datetime.timedelta(days=_pd)
            
            st_datestr = st_time.strftime('%Y%m%d')
            et_datestr = et_time.strftime('%Y%m%d')
            ex_time = et_time + datetime.timedelta(-1)
            ex_datestr = ex_time.strftime('%Y%m%d')
            
            
            #print et_datestr
            all_data = []
            results = {}
            os_data = []
            
            
            if _osid == "":
                xunhuan = [{'name':'All','id':'61,59,52'},{'name':'Android','id':'61'},{'name':'iOS','id':'52'},{'name':'WP7','id':'59'}]
            elif _device_type == "":
                xunhuan = [{'name':'All','id':'1,2'},{'name':'Phone','id':'1'},{'name':'Pad','id':'2'}]
            else:
                xunhuan = [{'name':'All'}]
            
            db = connectMySQL.connMySQL_stat()
            c=db.cursor()
            
            fanhui = {}
            
            
            nowmonth = time.strftime('%m',time.localtime(time.time()))

            cc = int(nowmonth)
            cf = []
            for i in xrange(cc,12):
                ch={}
                ch['year'] = 2011
                if len(str(i)) == 1:
                    i = "%s%s" % ("0",str(i))
                ch['month'] = i
                cf.append(ch)
        
            for i in xrange(1,cc+1):
                ch={}
                ch['year'] = 2012
                if len(str(i)) == 1:
                    i = "%s%s" % ("0",str(i))
                ch['month'] = i
                cf.append(ch)
            
            chh = []
            for i in cf[::-1]:
                chh.append(i)
            cf = chh
            
            #print cf[11]
            ghenglie = ""
            for cfv in cf:
                ghenglie += u"<th>%s/%s</th>" % (cfv['year'],cfv['month'])
            
            
            
            for vxunhuan in xrange(len(xunhuan)):
                
                #省市概览表头
                g_prov_table = "<div class=\"csv-box-header\"><strong>省市占比年度概览</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydayvideoTableX1');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydayvideoTableX1');\" >下载</a></span><a href=\"javascript:getCSVData('citydayvideoTableX1');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>"
                
                g_prov_table += u"<div style='overflow:auto;height:200px;'><table class='new_silver_table' id='citydayvideoTableX1'  ><thead><tr><th onclick=\" tableSortingly('citydayvideoTableX1', 1,1); \"  id='citydayvideoTableX1th1' >序号</th><th>省市</th>"
                
                #城市概览表头
                g_city_table = "<div class=\"csv-box-header\"><strong>城市占比年度概览</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydayvideoTableX2');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydayvideoTableX2');\" >下载</a></span><a href=\"javascript:getCSVData('citydayvideoTableX2');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>"
                
                g_city_table += u"<div style='overflow:auto;height:200px;'><table class='new_silver_table' id='citydayvideoTableX2'  ><thead><tr><th onclick=\" tableSortingly('citydayvideoTableX2', 1,1); \"  id='citydayvideoTableX2th1' >序号</th><th>城市</th>"
                
                table_msg = "从2012/06/26开始"
                
                #省市明细表头
                #m_prov_table = "<div class=\"csv-box-header\"><strong>省市明细(%s-%s)</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydayvideoTableX3');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydayvideoTableX3');\" >下载</a></span><a href=\"javascript:getCSVData('citydayvideoTableX3');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>" % (cnsort.fordate(st_datestr,1),cnsort.fordate(ex_datestr,1))
                m_prov_table = "<div class=\"csv-box-header\"><strong>省市明细(%s)</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydayvideoTableX3');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydayvideoTableX3');\" >下载</a></span><a href=\"javascript:getCSVData('citydayvideoTableX3');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>" % table_msg
                
                m_prov_table += u"<div style='overflow:auto;height:200px;'><table class='new_silver_table' id='citydayvideoTableX3'  ><thead><tr><th onclick=\" tableSortingly('citydayvideoTableX3', 1,1); \"  id='citydayvideoTableX3th1' >序号</th><th>省市</th><th>访问次数</th><th>占比</th>"
                
                #城市明细表头
                #m_city_table = "<div class=\"csv-box-header\"><strong>城市明细(%s-%s)</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydayvideoTableX4');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydayvideoTableX4');\" >下载</a></span><a href=\"javascript:getCSVData('citydayvideoTableX4');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>" % (cnsort.fordate(st_datestr,1),cnsort.fordate(ex_datestr,1))
                m_city_table = "<div class=\"csv-box-header\"><strong>城市明细(%s)</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydayvideoTableX4');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydayvideoTableX4');\" >下载</a></span><a href=\"javascript:getCSVData('citydayvideoTableX4');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>" % table_msg
                
                m_city_table += u"<div style='overflow:auto;height:200px;'><table class='new_silver_table' id='citydayvideoTableX4'  ><thead><tr><th onclick=\" tableSortingly('citydayvideoTableX4', 1,1); \"  id='citydayvideoTableX4th1' >序号</th><th>城市</th><th>访问次数</th><th>占比</th>"
                
                #省市明细表开始
                keylist = []
                mshengzong = []
                if _osid == "":
                    if _osid == "" and _device_type == "":
                        sql = "SELECT sum(a.uv),coalesce(b.prov_cn,'未知') FROM `stat_day_total` a left join `stat_city_dict` b   on a.prov = b.cprov_id   WHERE a.date >= '%s' and a.date < '%s' and  a.business_type = 2 and a.pid_stat = 1 and a.os_id in (%s) and a.device_type in (1,2) and a.partner_mode in (1,2,3,8) and a.prov != 'ALL' and a.city = 'ALL' and a.ver = 'ALL' group by coalesce(b.prov_cn,'未知') order by sum(a.uv) desc " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'])
                    else:
                        sql = "SELECT sum(a.uv),coalesce(b.prov_cn,'未知') FROM `stat_day_total` a left join `stat_city_dict` b   on a.prov = b.cprov_id WHERE a.date >= '%s' and a.date < '%s' and  a.business_type = 2 and a.pid_stat = 1 and a.os_id in (%s) and a.device_type in (%s) and a.partner_mode in (1,2,3,8) and a.prov != 'ALL' and a.city = 'ALL' and a.ver = 'ALL' group by coalesce(b.prov_cn,'未知') order by sum(a.uv) desc " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type)
                elif _device_type == "":
                    sql = "SELECT sum(a.uv),coalesce(b.prov_cn,'未知') FROM `stat_day_total` a left join `stat_city_dict` b   on a.prov = b.cprov_id WHERE a.date >= '%s' and a.date < '%s'  and  a.business_type = 2 and a.pid_stat = 1 and a.os_id in (%s) and a.device_type in (%s) and a.partner_mode in (1,2,3,8) and a.prov != 'ALL' and a.city = 'ALL' and a.ver = 'ALL' group by coalesce(b.prov_cn,'未知') order by sum(a.uv) desc " % (st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'])
                else:
                    sql = "SELECT sum(a.uv),coalesce(b.prov_cn,'未知') FROM `stat_day_total` a left join `stat_city_dict` b   on a.prov = b.cprov_id WHERE date >= '%s' and a.date < '%s' and  a.business_type = 2 and a.pid_stat = 1 and a.os_id in (%s) and a.device_type in (%s) and a.partner_mode in (1,2,3,8) and a.prov != 'ALL' and a.city = 'ALL' and a.ver = 'ALL' group by coalesce(b.prov_cn,'未知') order by sum(a.uv) desc " % (st_datestr,et_datestr,_osid,_device_type)
                #print sql
                c.execute(sql)  
                result = c.fetchall()
                keyprovlist = []                    
                for vv in result:
                    keyprovlist.append([vv[0],vv[1]])
                    mshengzong.append(vv[0])
                jishu = 1
                bingtuprovx="["
                bingtuprovy="["
                for i in xrange(len(keyprovlist)):
                    bg = ""
                    if jishu % 2 == 0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                        
                    xian = keyprovlist[i][0]
                    zong = sum(mshengzong)
                    try:    
                        a = xian/zong
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        m_prov_table += "<tr %s><td>%s</td><td>%s</td><td>%s</td><td>%s0%%</td></tr>" % (bg,jishu,keyprovlist[i][1],cnsort.num2money(xian),(zhanbi)*100)
                    else:
                        m_prov_table += "<tr %s><td>%s</td><td>%s</td><td>%s</td><td>%s%%</td></tr>" % (bg,jishu,keyprovlist[i][1],cnsort.num2money(xian),(zhanbi)*100)
                    
                    if jishu <= 10:
                        bingtuprovx += "'%s'," % keyprovlist[i][1]
                        bingtuprovy += "%s," % keyprovlist[i][0]
                    
                    
                    jishu = jishu + 1
                
                bingtuprovx += "]"
                bingtuprovy += "]"
                m_prov_table += "</table></div>"
                
                
                #print bingtuprovy
                
                
                #城市明细表开始
                keylist = []
                mshengzong = []
                if _osid == "":
                    if _osid == "" and _device_type == "":
                        sql = "SELECT sum(a.uv),coalesce(b.city_cn,'未知') FROM `stat_day_total` a left join `stat_city_dict` b   on a.city = b.ccity_id   WHERE a.date >= '%s' and a.date < '%s' and  a.business_type = 2 and a.pid_stat = 1 and a.os_id in (%s) and a.device_type in (1,2) and a.partner_mode in (1,2,3,8) and a.ver = 'ALL' and a.city != 'ALL' and prov = 'ALL' group by coalesce(b.city_cn,'未知') order by sum(a.uv) desc " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'])
                    else:
                        sql = "SELECT sum(a.uv),coalesce(b.city_cn,'未知') FROM `stat_day_total` a left join `stat_city_dict` b   on a.city = b.ccity_id WHERE a.date >= '%s' and a.date < '%s' and  a.business_type = 2 and a.pid_stat = 1 and a.os_id in (%s) and a.device_type in (%s) and a.partner_mode in (1,2,3,8) and a.ver = 'ALL' and a.city != 'ALL' and prov = 'ALL' group by coalesce(b.city_cn,'未知') order by sum(a.uv) desc " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type)
                elif _device_type == "":
                    sql = "SELECT sum(a.uv),coalesce(b.city_cn,'未知') FROM `stat_day_total` a left join `stat_city_dict` b   on a.city = b.ccity_id WHERE a.date >= '%s' and a.date < '%s'  and  a.business_type = 2 and a.pid_stat = 1 and a.os_id in (%s) and a.device_type in (%s) and a.partner_mode in (1,2,3,8) and a.ver = 'ALL' and a.city != 'ALL' and prov = 'ALL' group by coalesce(b.city_cn,'未知') order by sum(a.uv) desc " % (st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'])
                else:
                    sql = "SELECT sum(a.uv),coalesce(b.city_cn,'未知') FROM `stat_day_total` a left join `stat_city_dict` b   on a.city = b.ccity_id WHERE date >= '%s' and a.date < '%s' and  a.business_type = 2 and a.pid_stat = 1 and a.os_id in (%s) and a.device_type in (%s) and a.partner_mode in (1,2,3,8) and a.ver = 'ALL' and a.city != 'ALL' and prov = 'ALL' group by coalesce(b.city_cn,'未知') order by sum(a.uv) desc " % (st_datestr,et_datestr,_osid,_device_type)
                    
                c.execute(sql)  
                result = c.fetchall()
                keycitylist = []                    
                for vv in result:
                    keycitylist.append([vv[0],vv[1]])
                    mshengzong.append(vv[0])
                jishu = 1
                bingtucityx="["
                bingtucityy="["
                for i in xrange(len(keycitylist)):
                    bg = ""
                    if jishu % 2 == 0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                        
                    xian = keycitylist[i][0]
                    zong = sum(mshengzong)
                    try:    
                        a = xian/zong
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        m_city_table += "<tr %s><td>%s</td><td>%s</td><td>%s</td><td>%s0%%</td></tr>" % (bg,jishu,keycitylist[i][1],cnsort.num2money(xian),(zhanbi)*100)
                    else:
                        m_city_table += "<tr %s><td>%s</td><td>%s</td><td>%s</td><td>%s%%</td></tr>" % (bg,jishu,keycitylist[i][1],cnsort.num2money(xian),(zhanbi)*100)
                    
                    if jishu <= 10:
                        bingtucityx += "'%s'," % keycitylist[i][1]
                        bingtucityy += "%s," % keycitylist[i][0]
                    
                    
                    jishu = jishu + 1
                
                bingtucityx += "]"
                bingtucityy += "]"
                m_city_table += "</table></div>"
                
                #print m_city_table
                
                m_table = "%s%s" % (m_prov_table,m_city_table)
                
                #省市概览表开始
                g_prov_table += ghenglie
                endbdate = "%s%s01" % (cf[11]['year'],cf[11]['month'])
                zuihouyitian = calendar.monthrange(cf[0]['year'],int(cf[0]['month']))
                startbdate = "%s%s%s" % (cf[0]['year'],cf[0]['month'],zuihouyitian[1])
                
                #print startbdate
                
                if _osid == "":
                    if _osid == "" and _device_type == "":
                        sql = "SELECT sum(a.uv),coalesce(b.prov_cn,'未知'),coalesce(b.city_cn,'未知'),date FROM `stat_day_total` a left join `stat_city_dict` b on a.prov = b.cprov_id and a.city = b.ccity_id WHERE a.date <= '%s' and a.date >= '%s' and  a.business_type = 2 and a.pid_stat = 1 and a.os_id in (%s) and a.device_type in (1,2) and a.partner_mode in (1,2,3,8) and a.prov != 'ALL' and a.city != 'ALL' and a.ver = 'ALL' group by coalesce(b.prov_cn,'未知'),coalesce(b.city_cn,'未知'),a.date  " % (startbdate,endbdate,xunhuan[vxunhuan]['id'])
                    else:
                        sql = "SELECT sum(uv),coalesce(b.prov_cn,'未知'),coalesce(b.city_cn,'未知'),date FROM `stat_day_total` a left join `stat_city_dict` b on a.prov = b.cprov_id and a.city = b.ccity_id  WHERE a.date <= '%s' and a.date >= '%s' and  a.business_type = 2 and a.pid_stat = 1 and a.os_id in (%s) and a.device_type in (%s) and a.partner_mode in (1,2,3,8) and a.prov != 'ALL' and a.city != 'ALL' and a.ver = 'ALL' group by coalesce(b.prov_cn,'未知'),coalesce(b.city_cn,'未知'),a.date " % (startbdate,endbdate,xunhuan[vxunhuan]['id'],_device_type)
                elif _device_type == "":
                    sql = "SELECT sum(uv),coalesce(b.prov_cn,'未知'),coalesce(b.city_cn,'未知'),date FROM `stat_day_total` a left join `stat_city_dict` b on a.prov = b.cprov_id and a.city = b.ccity_id  WHERE a.date <= '%s' and a.date >= '%s'  and  a.business_type = 2 and a.pid_stat = 1 and a.os_id in (%s) and a.device_type in (%s) and a.partner_mode in (1,2,3,8) and a.prov != 'ALL' and a.city != 'ALL' and a.ver = 'ALL'  group by coalesce(b.prov_cn,'未知'),coalesce(b.city_cn,'未知'),a.date " % (startbdate,endbdate,_osid,xunhuan[vxunhuan]['id'])
                else:
                    sql = "SELECT sum(uv),coalesce(b.prov_cn,'未知'),coalesce(b.city_cn,'未知'),date FROM `stat_day_total` a left join `stat_city_dict` b on a.prov = b.cprov_id and a.city = b.ccity_id   WHERE a.date <= '%s' and a.date >= '%s' and  a.business_type = 2 and a.pid_stat = 1 and a.os_id in (%s) and a.device_type in (%s) and a.partner_mode in (1,2,3,8) and a.prov != 'ALL' and a.city != 'ALL' and a.ver = 'ALL'  group by coalesce(b.prov_cn,'未知'),coalesce(b.city_cn,'未知'),a.date " % (startbdate,endbdate,_osid,_device_type)
                #print sql
                c.execute(sql)  
                bresult = c.fetchall()
                
                print sql
                
                kpl = []
                for i in xrange(len(keyprovlist)):
                    hangzong = []
                    ck2 = []
                    for j in xrange(len(cf)):
                        sk = []
                        dk = []
                        for jjj in bresult:
                            ccdd = str(jjj[3])
                            p1 = "%s%s" % (cf[j]['year'],cf[j]['month'])
                            if jjj[1] == keyprovlist[i][1] and ccdd.find(p1) != -1:
                                sk.append(int(jjj[0]))
                                dk.append(int(jjj[0]))
                            else:
                                sk.append(0)
                                dk.append(0)
                        hangzong.append(sum(sk))
                        ck2.append(sum(dk))
                    kpl.append({'zongshu':sum(hangzong),'shulist':ck2})    
                
                
                
                jishu = 1
                for i in xrange(len(kpl)):
                    bg = ""
                    if jishu % 2 == 0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                    g_prov_table += "<tr %s><td>%s</td><td>%s</td>" % (bg,jishu,keyprovlist[i][1])
                    
                        
                    for j in xrange(len(kpl[i]['shulist'])):
                        xian = kpl[i]['shulist'][j]
                        shang = kpl[i-1]['shulist'][j]
                        zong = kpl[i]['zongshu']
                        
                        try:    
                            a = xian/zong
                        except:
                            a = 0
                        zhanbi = round(a,4)
                        
                        
                        cha = xian - shang
                            
                        if cha > 0:
                            jiantou = "<span class='inc_tag' style='margin-left: 5px;' title='0%'><b> ↑ </b></span>"
                        elif cha < 0:
                            jiantou = "<span class='des_tag' style='margin-left: 5px;' title='0%'><b> ↓ </b></span>"
                        else:
                            jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
                            
                        if i == 0:
                            jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
                        
                        nl = str(zhanbi).split(".")
                        if len(str(nl[1])) < 4:
                            g_prov_table += "<td>%s0%%</td>" % (zhanbi*100)
                        else:
                            g_prov_table += "<td>%s%%</td>" % (zhanbi*100) 
                    
                    g_prov_table += "</tr>"
                    jishu = jishu + 1
                
                g_prov_table +="</table></div>"
                
                
                #城市概览表开始
                
                g_city_table += ghenglie
                
                startbdate = "%s%s01" % (cf[0]['year'],cf[0]['month'])
                zuihouyitian = calendar.monthrange(cf[11]['year'],int(cf[11]['month']))
                endbdate = "%s%s%s" % (cf[11]['year'],cf[11]['month'],zuihouyitian[1])
                
                #print startbdate
                
                kpl = []
                for i in xrange(len(keycitylist)):
                    hangzong = []
                    ck2 = []
                    for j in xrange(len(cf)):
                        sk = []
                        dk = []
                        for jjj in bresult:
                            ccdd = str(jjj[3])
                            p1 = "%s%s" % (cf[j]['year'],cf[j]['month'])
                            if jjj[2] == keycitylist[i][1] and ccdd.find(p1) != -1:
                                sk.append(int(jjj[0]))
                                dk.append(int(jjj[0]))
                            else:
                                sk.append(0)
                                dk.append(0)
                        hangzong.append(sum(sk))
                        ck2.append(sum(dk))
                    kpl.append({'zongshu':sum(hangzong),'shulist':ck2})    
                
                
                
                jishu = 1
                for i in xrange(len(kpl)):
                    bg = ""
                    if jishu % 2 == 0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                    g_city_table += "<tr %s><td>%s</td><td>%s</td>" % (bg,jishu,keycitylist[i][1])
                    
                        
                    for j in xrange(len(kpl[i]['shulist'])):
                        xian = kpl[i]['shulist'][j]
                        shang = kpl[i-1]['shulist'][j]
                        zong = kpl[i]['zongshu']
                        
                        try:    
                            a = xian/zong
                        except:
                            a = 0
                        zhanbi = round(a,4)
                        
                        cha = xian - shang
                            
                        if cha > 0:
                            jiantou = "<span class='inc_tag' style='margin-left: 5px;' title='0%'><b> ↑ </b></span>"
                        elif cha < 0:
                            jiantou = "<span class='des_tag' style='margin-left: 5px;' title='0%'><b> ↓ </b></span>"
                        else:
                            jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
                            
                        if i == 0:
                            jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
                        
                        nl = str(zhanbi).split(".")
                        if len(str(nl[1])) < 4:
                            g_city_table += "<td>%s0%%</td>" % (zhanbi*100)
                        else:
                            g_city_table += "<td>%s%%</td>" % (zhanbi*100) 
                    
                    g_city_table += "</tr>"
                    jishu = jishu + 1
                
                g_city_table +="</table></div>"
                
                g_table = "%s%s" % (g_prov_table,g_city_table)
                
                fv = {}
                
                fv['mtable'] = m_table
                fv['gtable'] = g_table
                fv['bingtuprovx'] = bingtuprovx
                fv['bingtuprovy'] = bingtuprovy
                fv['bingtucityx'] = bingtucityx
                fv['bingtucityy'] = bingtucityy

                
                fanhui[xunhuan[vxunhuan]['name']] = fv
                
                
            
            c.close()
            db.close()
            _url = hashlib.md5(_url)
            _url.digest()
            try:
                mc.set(_url.hexdigest(),fanhui,1024*1024)
            except:
                pass
        else:
            fanhui = m_value
        self.write(fanhui)
        self.finish()  
        
        
class CityDayPaike_copy(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        
        
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        m_value = mc.get(_md5.hexdigest()) or {}
        #print m_value
        
        if settings.cache_on == 0:
            m_value = {}
        
        if not m_value:
        
            
            try:
                st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                return
            
            if not _pd:
                ed_time = datetime.datetime.now()
                delta = ed_time - st_time 
                _pd =  abs(delta.days)
            
            _pd = int(_pd)
            et_time = st_time + datetime.timedelta(days=_pd)
            
            st_datestr = st_time.strftime('%Y%m%d')
            et_datestr = et_time.strftime('%Y%m%d')
            ex_time = et_time + datetime.timedelta(-1)
            ex_datestr = ex_time.strftime('%Y%m%d')
            
            
            #print et_datestr
            all_data = []
            results = {}
            os_data = []
            
            
            if _osid == "":
                xunhuan = [{'name':'All','id':'61,59,52'},{'name':'Android','id':'61'},{'name':'iOS','id':'52'},{'name':'WP7','id':'59'}]
            elif _device_type == "":
                xunhuan = [{'name':'All','id':'1,2'},{'name':'Phone','id':'1'},{'name':'Pad','id':'2'}]
            else:
                xunhuan = [{'name':'All'}]
            
            db = connectMySQL.connMySQL_stat()
            c=db.cursor()
            
            fanhui = {}
            
            
            nowmonth = time.strftime('%m',time.localtime(time.time()))

            cc = int(nowmonth)
            cf = []
            for i in xrange(cc,12):
                ch={}
                ch['year'] = 2011
                if len(str(i)) == 1:
                    i = "%s%s" % ("0",str(i))
                ch['month'] = i
                cf.append(ch)
        
            for i in xrange(1,cc+1):
                ch={}
                ch['year'] = 2012
                if len(str(i)) == 1:
                    i = "%s%s" % ("0",str(i))
                ch['month'] = i
                cf.append(ch)
            
            chh = []
            for i in cf[::-1]:
                chh.append(i)
            cf = chh
            ghenglie = ""
            for cfv in cf:
                ghenglie += u"<th>%s/%s</th>" % (cfv['year'],cfv['month'])
            
            
            
            for vxunhuan in xrange(len(xunhuan)):
                
                table_msg = "从2012/06/26开始"
                
                #省市概览表头
                g_prov_table = "<div class=\"csv-box-header\"><strong>省市占比年度概览</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydaypaikeTableX1');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydaypaikeTableX1');\" >下载</a></span><a href=\"javascript:getCSVData('citydaypaikeTableX1');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>"
                
                g_prov_table += u"<div style='overflow:auto;height:200px;'><table class='new_silver_table' id='citydaypaikeTableX1'  ><thead><tr><th onclick=\" tableSortingly('citydaypaikeTableX1', 1,1); \"  id='citydaypaikeTableX1th1' >序号</th><th>省市</th>"
                
                #城市概览表头
                g_city_table = "<div class=\"csv-box-header\"><strong>城市占比年度概览</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydaypaikeTableX2');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydaypaikeTableX2');\" >下载</a></span><a href=\"javascript:getCSVData('citydaypaikeTableX2');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>"
                
                g_city_table += u"<div style='overflow:auto;height:200px;'><table class='new_silver_table' id='citydaypaikeTableX2'  ><thead><tr><th onclick=\" tableSortingly('citydaypaikeTableX2', 1,1); \"  id='citydaypaikeTableX2th1' >序号</th><th>城市</th>"
                
                
                #省市明细表头
                #m_prov_table = "<div class=\"csv-box-header\"><strong>省市明细(%s-%s)</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydaypaikeTableX3');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydaypaikeTableX3');\" >下载</a></span><a href=\"javascript:getCSVData('citydaypaikeTableX3');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>" % (cnsort.fordate(st_datestr,1),cnsort.fordate(ex_datestr,1))
                
                m_prov_table = "<div class=\"csv-box-header\"><strong>省市明细(%s)</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydaypaikeTableX3');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydaypaikeTableX3');\" >下载</a></span><a href=\"javascript:getCSVData('citydaypaikeTableX3');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>" % table_msg
                
                m_prov_table += u"<div style='overflow:auto;height:200px;'><table class='new_silver_table' id='citydaypaikeTableX3'  ><thead><tr><th onclick=\" tableSortingly('citydaypaikeTableX3', 1,1); \"  id='citydaypaikeTableX3th1' >序号</th><th>省市</th><th>访问次数</th><th>占比</th>"
                
                #城市明细表头
                #m_city_table = "<div class=\"csv-box-header\"><strong>城市明细(%s-%s)</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydaypaikeTableX4');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydaypaikeTableX4');\" >下载</a></span><a href=\"javascript:getCSVData('citydaypaikeTableX4');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>" % (cnsort.fordate(st_datestr,1),cnsort.fordate(ex_datestr,1))
                m_city_table = "<div class=\"csv-box-header\"><strong>城市明细(%s)</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydaypaikeTableX4');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydaypaikeTableX4');\" >下载</a></span><a href=\"javascript:getCSVData('citydaypaikeTableX4');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>" % table_msg
                
                m_city_table += u"<div style='overflow:auto;height:200px;'><table class='new_silver_table' id='citydaypaikeTableX4'  ><thead><tr><th onclick=\" tableSortingly('citydaypaikeTableX4', 1,1); \"  id='citydaypaikeTableX4th1' >序号</th><th>城市</th><th>访问次数</th><th>占比</th>"
                
                #省市明细表开始
                keylist = []
                mshengzong = []
                if _osid == "":
                    if _osid == "" and _device_type == "":
                        sql = "SELECT sum(a.uv),coalesce(b.prov_cn,'未知') FROM `stat_day_paike` a left join `stat_city_dict` b   on a.prov = b.cprov_id   WHERE a.date >= '%s' and a.date < '%s' and  a.business_type = 4 and a.pid_stat = 1 and a.os_id in (%s) and a.device_type in (1,2) and a.partner_mode in (1,2,3,8) and a.prov != 'ALL' and a.city = 'ALL' and ver = 'ALL' group by coalesce(b.prov_cn,'未知') order by sum(a.uv) desc " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'])
                    else:
                        sql = "SELECT sum(a.uv),coalesce(b.prov_cn,'未知') FROM `stat_day_paike` a left join `stat_city_dict` b   on a.prov = b.cprov_id WHERE a.date >= '%s' and a.date < '%s' and  a.business_type = 4 and a.pid_stat = 1 and a.os_id in (%s) and a.device_type in (%s) and a.partner_mode in (1,2,3,8) and a.prov != 'ALL' and a.city = 'ALL' and ver = 'ALL' group by coalesce(b.prov_cn,'未知') order by sum(a.uv) desc " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type)
                elif _device_type == "":
                    sql = "SELECT sum(a.uv),coalesce(b.prov_cn,'未知') FROM `stat_day_paike` a left join `stat_city_dict` b   on a.prov = b.cprov_id WHERE a.date >= '%s' and a.date < '%s'  and  a.business_type = 4 and a.pid_stat = 1 and a.os_id in (%s) and a.device_type in (%s) and a.partner_mode in (1,2,3,8) and a.prov != 'ALL' and a.city = 'ALL' and ver = 'ALL' group by coalesce(b.prov_cn,'未知') order by sum(a.uv) desc " % (st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'])
                else:
                    sql = "SELECT sum(a.uv),coalesce(b.prov_cn,'未知') FROM `stat_day_paike` a left join `stat_city_dict` b   on a.prov = b.cprov_id WHERE date >= '%s' and a.date < '%s' and  a.business_type = 4 and a.pid_stat = 1 and a.os_id in (%s) and a.device_type in (%s) and a.partner_mode in (1,2,3,8) and a.prov != 'ALL' and a.city = 'ALL' and ver = 'ALL' group by coalesce(b.prov_cn,'未知') order by sum(a.uv) desc " % (st_datestr,et_datestr,_osid,_device_type)
                #print sql
                c.execute(sql)  
                result = c.fetchall()
                keyprovlist = []                    
                for vv in result:
                    keyprovlist.append([vv[0],vv[1]])
                    mshengzong.append(vv[0])
                jishu = 1
                bingtuprovx="["
                bingtuprovy="["
                for i in xrange(len(keyprovlist)):
                    bg = ""
                    if jishu % 2 == 0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                        
                    xian = keyprovlist[i][0]
                    zong = sum(mshengzong)
                    try:    
                        a = xian/zong
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        m_prov_table += "<tr %s><td>%s</td><td>%s</td><td>%s</td><td>%s0%%</td></tr>" % (bg,jishu,keyprovlist[i][1],cnsort.num2money(xian),(zhanbi)*100)
                    else:
                        m_prov_table += "<tr %s><td>%s</td><td>%s</td><td>%s</td><td>%s%%</td></tr>" % (bg,jishu,keyprovlist[i][1],cnsort.num2money(xian),(zhanbi)*100)
                    
                    if jishu <= 10:
                        bingtuprovx += "'%s'," % keyprovlist[i][1]
                        bingtuprovy += "%s," % keyprovlist[i][0]
                    
                    
                    jishu = jishu + 1
                
                bingtuprovx += "]"
                bingtuprovy += "]"
                m_prov_table += "</table></div>"
                
                
                #print bingtuprovy
                
                
                #城市明细表开始
                keylist = []
                mshengzong = []
                if _osid == "":
                    if _osid == "" and _device_type == "":
                        sql = "SELECT sum(a.uv),coalesce(b.city_cn,'未知') FROM `stat_day_paike` a left join `stat_city_dict` b   on a.city = b.ccity_id   WHERE a.date >= '%s' and a.date < '%s' and  a.business_type = 4 and a.pid_stat = 1 and a.os_id in (%s) and a.device_type in (1,2) and a.partner_mode in (1,2,3,8) and a.ver = 'ALL' and a.city != 'ALL' and a.prov = 'ALL' group by coalesce(b.city_cn,'未知') order by sum(a.uv) desc " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'])
                    else:
                        sql = "SELECT sum(a.uv),coalesce(b.city_cn,'未知') FROM `stat_day_paike` a left join `stat_city_dict` b   on a.city = b.ccity_id WHERE a.date >= '%s' and a.date < '%s' and  a.business_type = 4 and a.pid_stat = 1 and a.os_id in (%s) and a.device_type in (%s) and a.partner_mode in (1,2,3,8) and a.ver = 'ALL' and a.city != 'ALL' and a.prov = 'ALL' group by coalesce(b.city_cn,'未知') order by sum(a.uv) desc " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type)
                elif _device_type == "":
                    sql = "SELECT sum(a.uv),coalesce(b.city_cn,'未知') FROM `stat_day_paike` a left join `stat_city_dict` b   on a.city = b.ccity_id WHERE a.date >= '%s' and a.date < '%s'  and  a.business_type = 4 and a.pid_stat = 1 and a.os_id in (%s) and a.device_type in (%s) and a.partner_mode in (1,2,3,8) and a.ver = 'ALL' and a.city != 'ALL' and a.prov = 'ALL' group by coalesce(b.city_cn,'未知') order by sum(a.uv) desc " % (st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'])
                else:
                    sql = "SELECT sum(a.uv),coalesce(b.city_cn,'未知') FROM `stat_day_paike` a left join `stat_city_dict` b   on a.city = b.ccity_id WHERE date >= '%s' and a.date < '%s' and  a.business_type = 4 and a.pid_stat = 1 and a.os_id in (%s) and a.device_type in (%s) and a.partner_mode in (1,2,3,8) and a.ver = 'ALL' and a.city != 'ALL' and a.prov = 'ALL' group by coalesce(b.city_cn,'未知') order by sum(a.uv) desc " % (st_datestr,et_datestr,_osid,_device_type)
                    
                c.execute(sql)  
                result = c.fetchall()
                keycitylist = []                    
                for vv in result:
                    keycitylist.append([vv[0],vv[1]])
                    mshengzong.append(vv[0])
                jishu = 1
                bingtucityx="["
                bingtucityy="["
                for i in xrange(len(keycitylist)):
                    bg = ""
                    if jishu % 2 == 0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                        
                    xian = keycitylist[i][0]
                    zong = sum(mshengzong)
                    try:    
                        a = xian/zong
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        m_city_table += "<tr %s><td>%s</td><td>%s</td><td>%s</td><td>%s0%%</td></tr>" % (bg,jishu,keycitylist[i][1],cnsort.num2money(xian),(zhanbi)*100)
                    else:
                        m_city_table += "<tr %s><td>%s</td><td>%s</td><td>%s</td><td>%s%%</td></tr>" % (bg,jishu,keycitylist[i][1],cnsort.num2money(xian),(zhanbi)*100)
                    
                    if jishu <= 10:
                        bingtucityx += "'%s'," % keycitylist[i][1]
                        bingtucityy += "%s," % keycitylist[i][0]
                    
                    
                    jishu = jishu + 1
                
                bingtucityx += "]"
                bingtucityy += "]"
                m_city_table += "</table></div>"
                
                #print m_city_table
                
                m_table = "%s%s" % (m_prov_table,m_city_table)
                
                #省市概览表开始
                g_prov_table += ghenglie
            
                endbdate = "%s%s01" % (cf[11]['year'],cf[11]['month'])
                zuihouyitian = calendar.monthrange(cf[0]['year'],int(cf[0]['month']))
                startbdate = "%s%s%s" % (cf[0]['year'],cf[0]['month'],zuihouyitian[1])
                
                #print startbdate
                
                if _osid == "":
                    if _osid == "" and _device_type == "":
                        sql = "SELECT sum(a.uv),coalesce(b.prov_cn,'未知'),coalesce(b.city_cn,'未知'),date FROM `stat_day_paike` a left join `stat_city_dict` b on a.prov = b.cprov_id and a.city = b.ccity_id WHERE a.date <= '%s' and a.date >= '%s' and  a.business_type = 4 and a.pid_stat = 1 and a.os_id in (%s) and a.device_type in (1,2) and a.partner_mode in (1,2,3,8) and a.prov != 'ALL' and a.city != 'ALL' and ver = 'ALL' group by coalesce(b.prov_cn,'未知'),coalesce(b.city_cn,'未知'),a.date  " % (startbdate,endbdate,xunhuan[vxunhuan]['id'])
                    else:
                        sql = "SELECT sum(uv),coalesce(b.prov_cn,'未知'),coalesce(b.city_cn,'未知'),date FROM `stat_day_paike` a left join `stat_city_dict` b on a.prov = b.cprov_id and a.city = b.ccity_id  WHERE a.date <= '%s' and a.date >= '%s' and  a.business_type = 4 and a.pid_stat = 1 and a.os_id in (%s) and a.device_type in (%s) and a.partner_mode in (1,2,3,8) and a.prov != 'ALL' and a.city != 'ALL' and ver = 'ALL' group by coalesce(b.prov_cn,'未知'),coalesce(b.city_cn,'未知'),a.date " % (startbdate,endbdate,xunhuan[vxunhuan]['id'],_device_type)
                elif _device_type == "":
                    sql = "SELECT sum(uv),coalesce(b.prov_cn,'未知'),coalesce(b.city_cn,'未知'),date FROM `stat_day_paike` a left join `stat_city_dict` b on a.prov = b.cprov_id and a.city = b.ccity_id  WHERE a.date <= '%s' and a.date >= '%s'  and  a.business_type = 4 and a.pid_stat = 1 and a.os_id in (%s) and a.device_type in (%s) and a.partner_mode in (1,2,3,8) and a.prov != 'ALL' and a.city != 'ALL' and ver = 'ALL'  group by coalesce(b.prov_cn,'未知'),coalesce(b.city_cn,'未知'),a.date " % (startbdate,endbdate,_osid,xunhuan[vxunhuan]['id'])
                else:
                    sql = "SELECT sum(uv),coalesce(b.prov_cn,'未知'),coalesce(b.city_cn,'未知'),date FROM `stat_day_paike` a left join `stat_city_dict` b on a.prov = b.cprov_id and a.city = b.ccity_id   WHERE a.date <= '%s' and a.date >= '%s' and  a.business_type = 4 and a.pid_stat = 1 and a.os_id in (%s) and a.device_type in (%s) and a.partner_mode in (1,2,3,8) and a.prov != 'ALL' and a.city != 'ALL' and ver = 'ALL'  group by coalesce(b.prov_cn,'未知'),coalesce(b.city_cn,'未知'),a.date " % (startbdate,endbdate,_osid,_device_type)
                #print sql
                c.execute(sql)  
                bresult = c.fetchall()
                
                #print sql
                
                kpl = []
                for i in xrange(len(keyprovlist)):
                    hangzong = []
                    ck2 = []
                    for j in xrange(len(cf)):
                        sk = []
                        dk = []
                        for jjj in bresult:
                            ccdd = str(jjj[3])
                            p1 = "%s%s" % (cf[j]['year'],cf[j]['month'])
                            if jjj[1] == keyprovlist[i][1] and ccdd.find(p1) != -1:
                                sk.append(int(jjj[0]))
                                dk.append(int(jjj[0]))
                            else:
                                sk.append(0)
                                dk.append(0)
                        hangzong.append(sum(sk))
                        ck2.append(sum(dk))
                    kpl.append({'zongshu':sum(hangzong),'shulist':ck2})    
                
                
                
                jishu = 1
                for i in xrange(len(kpl)):
                    bg = ""
                    if jishu % 2 == 0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                    g_prov_table += "<tr %s><td>%s</td><td>%s</td>" % (bg,jishu,keyprovlist[i][1])
                    
                        
                    for j in xrange(len(kpl[i]['shulist'])):
                        xian = kpl[i]['shulist'][j]
                        shang = kpl[i-1]['shulist'][j]
                        zong = kpl[i]['zongshu']
                        
                        try:    
                            a = xian/zong
                        except:
                            a = 0
                        zhanbi = round(a,4)
                        
                        cha = xian - shang
                            
                        if cha > 0:
                            jiantou = "<span class='inc_tag' style='margin-left: 5px;' title='0%'><b> ↑ </b></span>"
                        elif cha < 0:
                            jiantou = "<span class='des_tag' style='margin-left: 5px;' title='0%'><b> ↓ </b></span>"
                        else:
                            jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
                            
                        if i == 0:
                            jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
                        
                        nl = str(zhanbi).split(".")
                        if len(str(nl[1])) < 4:
                            g_prov_table += "<td>%s0%%</td>" % (zhanbi*100) 
                        else:
                            g_prov_table += "<td>%s%%</td>" % (zhanbi*100) 
                    
                    g_prov_table += "</tr>"
                    jishu = jishu + 1
                
                g_prov_table +="</table></div>"
                
                
                #城市概览表开始
                
                g_city_table += ghenglie
                
                startbdate = "%s%s01" % (cf[0]['year'],cf[0]['month'])
                zuihouyitian = calendar.monthrange(cf[11]['year'],int(cf[11]['month']))
                endbdate = "%s%s%s" % (cf[11]['year'],cf[11]['month'],zuihouyitian[1])
                
                #print startbdate
                
                kpl = []
                for i in xrange(len(keycitylist)):
                    hangzong = []
                    ck2 = []
                    for j in xrange(len(cf)):
                        sk = []
                        dk = []
                        for jjj in bresult:
                            ccdd = str(jjj[3])
                            p1 = "%s%s" % (cf[j]['year'],cf[j]['month'])
                            if jjj[2] == keycitylist[i][1] and ccdd.find(p1) != -1:
                                sk.append(int(jjj[0]))
                                dk.append(int(jjj[0]))
                            else:
                                sk.append(0)
                                dk.append(0)
                        hangzong.append(sum(sk))
                        ck2.append(sum(dk))
                    kpl.append({'zongshu':sum(hangzong),'shulist':ck2})    
                
                
                
                jishu = 1
                for i in xrange(len(kpl)):
                    bg = ""
                    if jishu % 2 == 0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                    g_city_table += "<tr %s><td>%s</td><td>%s</td>" % (bg,jishu,keycitylist[i][1])
                    
                        
                    for j in xrange(len(kpl[i]['shulist'])):
                        xian = kpl[i]['shulist'][j]
                        shang = kpl[i-1]['shulist'][j]
                        zong = kpl[i]['zongshu']
                        
                        try:    
                            a = xian/zong
                        except:
                            a = 0
                        zhanbi = round(a,4)
                        
                        cha = xian - shang
                            
                        if cha > 0:
                            jiantou = "<span class='inc_tag' style='margin-left: 5px;' title='0%'><b> ↑ </b></span>"
                        elif cha < 0:
                            jiantou = "<span class='des_tag' style='margin-left: 5px;' title='0%'><b> ↓ </b></span>"
                        else:
                            jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
                            
                        if i == 0:
                            jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
                        
                        nl = str(zhanbi).split(".")
                        if len(str(nl[1])) < 4:
                            g_city_table += "<td>%s0%%</td>" % (zhanbi*100)
                        else:
                            g_city_table += "<td>%s%%</td>" % (zhanbi*100) 
                    
                    g_city_table += "</tr>"
                    jishu = jishu + 1
                
                g_city_table +="</table></div>"
                
                g_table = "%s%s" % (g_prov_table,g_city_table)
                
                fv = {}
                
                fv['mtable'] = m_table
                fv['gtable'] = g_table
                fv['bingtuprovx'] = bingtuprovx
                fv['bingtuprovy'] = bingtuprovy
                fv['bingtucityx'] = bingtucityx
                fv['bingtucityy'] = bingtucityy

                
                fanhui[xunhuan[vxunhuan]['name']] = fv
                
                
            
            c.close()
            db.close()
            _url = hashlib.md5(_url)
            _url.digest()
            try:
                mc.set(_url.hexdigest(),fanhui,1024*1024)
            except:
                pass
        else:
            fanhui = m_value
        self.write(fanhui)
        self.finish()


class CityDayPaike(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        _limit = self.get_argument('limit','10').strip()
        
        
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        m_value = mc.get(_md5.hexdigest()) or {}
        #print m_value
        
        if settings.cache_on == 0:
            m_value = {}
        
        if not m_value:
        
            
            try:
                st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                return
            
            if not _pd:
                ed_time = datetime.datetime.now()
                delta = ed_time - st_time 
                _pd =  abs(delta.days)
            
            _pd = int(_pd)
            et_time = st_time + datetime.timedelta(days=_pd)
            
            st_datestr = st_time.strftime('%Y%m%d')
            et_datestr = et_time.strftime('%Y%m%d')
            ex_time = et_time + datetime.timedelta(-1)
            ex_datestr = ex_time.strftime('%Y%m%d')
            
            
            #print et_datestr
            all_data = []
            results = {}
            os_data = []
            
            
            if _osid == "":
                xunhuan = [{'name':'All','id':'-1'},{'name':'Android','id':'61'},{'name':'iOS','id':'52'},{'name':'WP7','id':'59'}]
            elif _device_type == "":
                xunhuan = [{'name':'All','id':'-1'},{'name':'Phone','id':'1'},{'name':'Pad','id':'2'}]
            else:
                xunhuan = [{'name':'All'}]
            
            db = connectMySQL.connMySQL_stat()
            c=db.cursor()
            
            fanhui = {}
            
            
            nowmonth = time.strftime('%m',time.localtime(time.time()))

            cc = int(nowmonth)
            cf = []
            for i in xrange(cc,12):
                ch={}
                ch['year'] = 2011
                if len(str(i)) == 1:
                    i = "%s%s" % ("0",str(i))
                ch['month'] = i
                cf.append(ch)
        
            for i in xrange(1,cc+1):
                ch={}
                ch['year'] = 2012
                if len(str(i)) == 1:
                    i = "%s%s" % ("0",str(i))
                ch['month'] = i
                cf.append(ch)
            
            chh = []
            for i in cf[::-1]:
                chh.append(i)
            cf = chh
            ghenglie = ""
            for cfv in cf:
                ghenglie += u"<th>%s/%s</th>" % (cfv['year'],cfv['month'])
            
            
            
            for vxunhuan in xrange(len(xunhuan)):
                
                table_msg = ""
                
                #省市概览表头
                g_prov_table = "<div class=\"csv-box-header\"><strong>省市占比年度概览</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydaypaikeTableX1');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydaypaikeTableX1');\" >下载</a></span><a href=\"javascript:getCSVData('citydaypaikeTableX1');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>"
                
                g_prov_table += u"<div style='overflow:auto;height:200px;'><table class='new_silver_table' id='citydaypaikeTableX1'  ><thead><tr><th onclick=\" tableSortingly('citydaypaikeTableX1', 1,1); \"  id='citydaypaikeTableX1th1' >序号</th><th>省市</th>"
                
                #城市概览表头
                g_city_table = "<div class=\"csv-box-header\"><strong>城市占比年度概览</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydaypaikeTableX2');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydaypaikeTableX2');\" >下载</a></span><a href=\"javascript:getCSVData('citydaypaikeTableX2');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>"
                
                g_city_table += u"<div style='overflow:auto;height:200px;'><table class='new_silver_table' id='citydaypaikeTableX2'  ><thead><tr><th onclick=\" tableSortingly('citydaypaikeTableX2', 1,1); \"  id='citydaypaikeTableX2th1' >序号</th><th>城市</th>"
                
                
                #省市明细表头
                #m_prov_table = "<div class=\"csv-box-header\"><strong>省市明细(%s-%s)</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydaypaikeTableX3');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydaypaikeTableX3');\" >下载</a></span><a href=\"javascript:getCSVData('citydaypaikeTableX3');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>" % (cnsort.fordate(st_datestr,1),cnsort.fordate(ex_datestr,1))
                
                m_prov_table = "<div class=\"csv-box-header\"><strong>省市明细%s</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydaypaikeTableX3');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydaypaikeTableX3');\" >下载</a></span><a href=\"javascript:getCSVData('citydaypaikeTableX3');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>" % table_msg
                
                m_prov_table += u"<div style='overflow:auto;height:200px;'><table class='new_silver_table' id='citydaypaikeTableX3'  ><thead><tr><th onclick=\" tableSortingly('citydaypaikeTableX3', 1,1); \"  id='citydaypaikeTableX3th1' >序号</th><th>省市</th><th>用户数(日UV累计)</th><th>占比</th>"
                
                #城市明细表头
                #m_city_table = "<div class=\"csv-box-header\"><strong>城市明细(%s-%s)</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydaypaikeTableX4');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydaypaikeTableX4');\" >下载</a></span><a href=\"javascript:getCSVData('citydaypaikeTableX4');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>" % (cnsort.fordate(st_datestr,1),cnsort.fordate(ex_datestr,1))
                m_city_table = "<div class=\"csv-box-header\"><strong>城市明细%s</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('citydaypaikeTableX4');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('citydaypaikeTableX4');\" >下载</a></span><a href=\"javascript:getCSVData('citydaypaikeTableX4');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>" % table_msg
                
                m_city_table += u"<div style='overflow:auto;height:200px;'><table class='new_silver_table' id='citydaypaikeTableX4'  ><thead><tr><th onclick=\" tableSortingly('citydaypaikeTableX4', 1,1); \"  id='citydaypaikeTableX4th1' >序号</th><th>城市</th><th>用户数(日UV累计)</th><th>占比</th>"
                
                #省市明细表开始
                keylist = []
                mshengzong = []
                if _osid == "":
                    if _osid == "" and _device_type == "":
                        #sql = "SELECT sum(uv),prov FROM `result_paike_area` WHERE date >= '%s' and date < '%s' and  os_id = '%s'   group by prov order by sum(uv) desc  " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'])
                        
                        sql = "select sumtoal,prov,sumtoal/(select sum(uv) as total from `result_total_area` where date >= %s and date <= %s  and  os_id  = %s) total from (SELECT sum(uv) sumtoal,prov FROM `result_total_area` WHERE date >= %s and date <= %s  and  os_id  = %s group by prov ) a order by sumtoal desc  " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],st_datestr,et_datestr,xunhuan[vxunhuan]['id'])
                        
                        
                    else:
                        #sql = "SELECT sum(uv),prov FROM `result_paike_area` WHERE date >= '%s' and date < '%s' and  os_id = '%s' and device_type = '%s'  group by prov order by sum(uv) desc  " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type)
                        
                        sql = "select sumtoal,prov,sumtoal/(select sum(uv) as total from `result_total_area` where date >= %s and date <= %s  and  os_id  = %s and device_type = %s) total from (SELECT sum(uv) sumtoal,prov FROM `result_total_area` WHERE date >= %s and date <= %s  and  os_id  = %s and device_type = %s group by prov ) a order by sumtoal desc  " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type,st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type)
                        
                        
                elif _device_type == "":
                    #sql = "SELECT sum(uv),prov FROM `result_paike_area` WHERE date >= '%s' and date < '%s' and  os_id = '%s' and device_type = '%s'  group by prov order by sum(uv) desc  " % (st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'])
                    
                    sql = "select sumtoal,prov,sumtoal/(select sum(uv) as total from `result_total_area` where date >= %s and date <= %s  and  os_id  = %s and device_type = %s) total from (SELECT sum(uv) sumtoal,prov FROM `result_total_area` WHERE date >= %s and date <= %s  and  os_id  = %s and device_type = %s group by prov ) a order by sumtoal desc  " % (st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'],st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'])
                    
                else:
                    #sql = "SELECT sum(uv),prov FROM `result_paike_area` WHERE date >= '%s' and date < '%s' and  os_id = '%s' and device_type = '%s'  group by prov order by sum(uv) desc  " % (st_datestr,et_datestr,_osid,_device_type)
                    
                    
                    sql = "select sumtoal,prov,sumtoal/(select sum(uv) as total from `result_total_area` where date >= %s and date <= %s  and  os_id  = %s and device_type = %s) total from (SELECT sum(uv) sumtoal,prov FROM `result_total_area` WHERE date >= %s and date <= %s  and  os_id  = %s and device_type = %s group by prov ) a order by sumtoal desc  " % (st_datestr,et_datestr,_osid,_device_type,st_datestr,et_datestr,_osid,_device_type)
                    
                #print sql
                c.execute(sql)  
                result = c.fetchall()
                keyprovlist = []                    
                jishu = 1
                bingtuprovx="["
                bingtuprovy="["
                for i in result:
                    bg = ""
                    if jishu % 2 == 0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                        
                    xian = int(i[0])
                    
                    zhanbi = round(float(i[2]),4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        m_prov_table += "<tr %s><td>%s</td><td>%s</td><td>%s</td><td>%s0%%</td></tr>" % (bg,jishu,str(i[1]),cnsort.num2money(xian),(zhanbi)*100)
                    else:
                        m_prov_table += "<tr %s><td>%s</td><td>%s</td><td>%s</td><td>%s%%</td></tr>" % (bg,jishu,str(i[1]),cnsort.num2money(xian),(zhanbi)*100)
                    
                    if jishu <= 10:
                        bingtuprovx += "'%s'," % str(i[1])
                        bingtuprovy += "%s," % int(i[0])
                    
                    
                    jishu = jishu + 1
                
                bingtuprovx += "]"
                bingtuprovy += "]"
                m_prov_table += "</table></div>"
                
                
                #print bingtuprovy
                
                
                #城市明细表开始
                keylist = []
                mshengzong = []
                if _osid == "":
                    if _osid == "" and _device_type == "":
                        #sql = "SELECT sum(uv),city FROM `result_paike_area` WHERE date >= '%s' and date < '%s' and  os_id = '%s'   group by city order by sum(uv) desc  " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'])
                        sql = "select sumtoal,city,sumtoal/(select sum(uv) as total from `result_total_area` where date >= %s and date <= %s  and  os_id  = %s) total from (SELECT sum(uv) sumtoal,city FROM `result_total_area` WHERE date >= %s and date <= %s  and  os_id  = %s group by city ) a order by sumtoal desc  " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],st_datestr,et_datestr,xunhuan[vxunhuan]['id'])
                    else:
                        #sql = "SELECT sum(uv),city FROM `result_paike_area` WHERE date >= '%s' and date < '%s' and  os_id = '%s' and device_type = '%s'  group by city order by sum(uv) desc  " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type)
                        
                        sql = "select sumtoal,city,sumtoal/(select sum(uv) as total from `result_total_area` where date >= %s and date <= %s  and  os_id  = %s and device_type = %s) total from (SELECT sum(uv) sumtoal,city FROM `result_total_area` WHERE date >= %s and date <= %s  and  os_id  = %s and device_type = %s group by city ) a order by sumtoal desc  " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type,st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type)
                        
                elif _device_type == "":
                    #sql = "SELECT sum(uv),city FROM `result_paike_area` WHERE date >= '%s' and date < '%s' and  os_id = '%s' and device_type = '%s'  group by city order by sum(uv) desc  " % (st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'])
                    
                    sql = "select sumtoal,city,sumtoal/(select sum(uv) as total from `result_total_area` where date >= %s and date <= %s  and  os_id  = %s and device_type = %s) total from (SELECT sum(uv) sumtoal,city FROM `result_total_area` WHERE date >= %s and date <= %s  and  os_id  = %s and device_type = %s group by city ) a order by sumtoal desc  " % (st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'],st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'])
                    
                else:
                    #sql = "SELECT sum(uv),city FROM `result_paike_area` WHERE date >= '%s' and date < '%s' and  os_id = '%s' and device_type = '%s'  group by city order by sum(uv) desc  " % (st_datestr,et_datestr,_osid,_device_type)
                    
                    sql = "select sumtoal,city,sumtoal/(select sum(uv) as total from `result_total_area` where date >= %s and date <= %s  and  os_id  = %s and device_type = %s) total from (SELECT sum(uv) sumtoal,city FROM `result_total_area` WHERE date >= %s and date <= %s  and  os_id  = %s and device_type = %s group by city ) a order by sumtoal desc  " % (st_datestr,et_datestr,_osid,_device_type,st_datestr,et_datestr,_osid,_device_type)
                    
                c.execute(sql)  
                result = c.fetchall()
                keycitylist = []                    
                jishu = 1
                bingtucityx="["
                bingtucityy="["
                for i in result:
                    bg = ""
                    if jishu % 2 == 0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                        
                    xian = int(i[0])
                    
                    zhanbi = round(float(i[2]),4)
                    
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        m_city_table += "<tr %s><td>%s</td><td>%s</td><td>%s</td><td>%s0%%</td></tr>" % (bg,jishu,str(i[1]),cnsort.num2money(xian),(zhanbi)*100)
                    else:
                        m_city_table += "<tr %s><td>%s</td><td>%s</td><td>%s</td><td>%s%%</td></tr>" % (bg,jishu,str(i[1]),cnsort.num2money(xian),(zhanbi)*100)
                    
                    if jishu <= 10:
                        bingtucityx += "'%s'," % str(i[1])
                        bingtucityy += "%s," % int(i[0])
                    
                    
                    jishu = jishu + 1
                
                bingtucityx += "]"
                bingtucityy += "]"
                m_city_table += "</table></div>"
                
                #print m_city_table
                
                m_table = "%s%s" % (m_prov_table,m_city_table)
                
                #省市概览表开始
                g_prov_table += ghenglie
            
                endbdate = "%s%s01" % (cf[11]['year'],cf[11]['month'])
                zuihouyitian = calendar.monthrange(cf[0]['year'],int(cf[0]['month']))
                startbdate = "%s%s%s" % (cf[0]['year'],cf[0]['month'],zuihouyitian[1])
                
                #print startbdate
                """
                if _osid == "":
                    if _osid == "" and _device_type == "":
                        sql = "SELECT sum(uv),prov,city,date FROM `result_paike_area` WHERE date >= '%s' and date < '%s' and  os_id  = '%s' group by prov,city,date  " % (endbdate,startbdate,xunhuan[vxunhuan]['id'])
                    else:
                        sql = "SELECT sum(uv),prov,city,date FROM `result_paike_area` WHERE date >= '%s' and date < '%s' and  os_id  = '%s' and device_type = '%s' group by prov,city,date " % (endbdate,startbdate,xunhuan[vxunhuan]['id'],_device_type)
                elif _device_type == "":
                    sql = "SELECT sum(uv),prov,city,date FROM `result_paike_area` WHERE date >= '%s' and date < '%s' and  os_id  = '%s' and device_type = '%s' group by prov,city,date " % (endbdate,startbdate,_osid,xunhuan[vxunhuan]['id'])
                else:
                    sql = "SELECT sum(uv),prov,city,date FROM `result_paike_area` WHERE date >= '%s' and date < '%s' and  os_id  = '%s' and device_type = '%s' group by prov,city,date " % (endbdate,startbdate,_osid,_device_type)
                #print sql
                c.execute(sql)  
                bresult = c.fetchall()
                
                #print sql
                
                kpl = []
                for i in xrange(len(keyprovlist)):
                    hangzong = []
                    ck2 = []
                    for j in xrange(len(cf)):
                        sk = []
                        dk = []
                        for jjj in bresult:
                            ccdd = str(jjj[3])
                            p1 = "%s%s" % (cf[j]['year'],cf[j]['month'])
                            if jjj[1] == keyprovlist[i][1] and ccdd.find(p1) != -1:
                                sk.append(int(jjj[0]))
                                dk.append(int(jjj[0]))
                            else:
                                sk.append(0)
                                dk.append(0)
                        hangzong.append(sum(sk))
                        ck2.append(sum(dk))
                    kpl.append({'zongshu':sum(hangzong),'shulist':ck2})    
                
                
                
                jishu = 1
                for i in xrange(len(kpl)):
                    bg = ""
                    if jishu % 2 == 0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                    g_prov_table += "<tr %s><td>%s</td><td>%s</td>" % (bg,jishu,keyprovlist[i][1])
                    
                        
                    for j in xrange(len(kpl[i]['shulist'])):
                        xian = kpl[i]['shulist'][j]
                        zzong = []
                        
                        for kc in xrange(len(kpl)):
                            zzong.append(kpl[kc]['shulist'][j])
                        
                        zong = sum(zzong)
                        
                        try:    
                            a = xian/zong
                        except:
                            a = 0
                        zhanbi = round(a,4)
                        
                        
                        
                        nl = str(zhanbi).split(".")
                        if len(str(nl[1])) < 4:
                            g_prov_table += "<td>%s0%%</td>" % (zhanbi*100) 
                        else:
                            g_prov_table += "<td>%s%%</td>" % (zhanbi*100) 
                    
                    g_prov_table += "</tr>"
                    jishu = jishu + 1
                
                g_prov_table +="</table></div>"
                
                
                #城市概览表开始
                
                g_city_table += ghenglie
                
                startbdate = "%s%s01" % (cf[0]['year'],cf[0]['month'])
                zuihouyitian = calendar.monthrange(cf[11]['year'],int(cf[11]['month']))
                endbdate = "%s%s%s" % (cf[11]['year'],cf[11]['month'],zuihouyitian[1])
                
                #print startbdate
                
                kpl = []
                for i in xrange(len(keycitylist)):
                    hangzong = []
                    ck2 = []
                    for j in xrange(len(cf)):
                        sk = []
                        dk = []
                        for jjj in bresult:
                            ccdd = str(jjj[3])
                            p1 = "%s%s" % (cf[j]['year'],cf[j]['month'])
                            if jjj[2] == keycitylist[i][1] and ccdd.find(p1) != -1:
                                sk.append(int(jjj[0]))
                                dk.append(int(jjj[0]))
                            else:
                                sk.append(0)
                                dk.append(0)
                        hangzong.append(sum(sk))
                        ck2.append(sum(dk))
                    kpl.append({'zongshu':sum(hangzong),'shulist':ck2})    
                
                
                
                jishu = 1
                for i in xrange(len(kpl)):
                    bg = ""
                    if jishu % 2 == 0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                    g_city_table += "<tr %s><td>%s</td><td>%s</td>" % (bg,jishu,keycitylist[i][1])
                    
                        
                    for j in xrange(len(kpl[i]['shulist'])):
                        xian = kpl[i]['shulist'][j]
                        zzong = []
                        
                        for kc in xrange(len(kpl)):
                            zzong.append(kpl[kc]['shulist'][j])
                        
                        zong = sum(zzong)
                        
                        try:    
                            a = xian/zong
                        except:
                            a = 0
                        zhanbi = round(a,4)
                        
                        
                        
                        nl = str(zhanbi).split(".")
                        if len(str(nl[1])) < 4:
                            g_city_table += "<td>%s0%%</td>" % (zhanbi*100)
                        else:
                            g_city_table += "<td>%s%%</td>" % (zhanbi*100) 
                    
                    g_city_table += "</tr>"
                    jishu = jishu + 1
                
                g_city_table +="</table></div>"
                
                g_table = "%s%s" % (g_prov_table,g_city_table)
                """
                
               
                
                if _osid == "":
                    if _osid == "" and _device_type == "":
                        sql = "select `table` from result_paike_yeartable where startdate = '%s' and enddate = '%s'  and os_id = '%s'  " % (startbdate,endbdate,xunhuan[vxunhuan]['id'])
                    else:
                        sql = "select `table` from result_paike_yeartable where startdate = '%s' and enddate = '%s'  and os_id = '%s' and device_type = '%s' " % (startbdate,endbdate,xunhuan[vxunhuan]['id'],_device_type)
                elif _device_type == "":
                    sql = "select `table` from result_paike_yeartable where startdate = '%s' and enddate = '%s'  and os_id = '%s' and device_type = '%s' " % (startbdate,endbdate,_osid,xunhuan[vxunhuan]['id'])
                else:
                    sql = "select `table` from result_paike_yeartable where startdate = '%s' and enddate = '%s'  and os_id = '%s' and device_type = '%s' " % (startbdate,endbdate,_osid,_device_type)
                 
                c.execute(sql)  
                oneresult = c.fetchone()
                

                if oneresult != None:
                    g_table = oneresult[0]
                else:
                    g_table = "%s%s" % (g_prov_table,g_city_table)
                
                
                fv = {}
                
                fv['mtable'] = m_table
                fv['gtable'] = g_table
                fv['bingtuprovx'] = bingtuprovx
                fv['bingtuprovy'] = bingtuprovy
                fv['bingtucityx'] = bingtucityx
                fv['bingtucityy'] = bingtucityy

                
                fanhui[xunhuan[vxunhuan]['name']] = fv
                
                
            
            c.close()
            db.close()
            _url = hashlib.md5(_url)
            _url.digest()
            try:
                mc.set(_url.hexdigest(),fanhui,1024*1024)
            except:
                pass
        else:
            fanhui = m_value
        self.write(fanhui)
        self.finish()








class NewMainVideo_beifen(BaseHandler):
    def get(self): 
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        _pm = self.get_argument('pm','').strip()
        _items = self.get_argument('items','UV,VV,').strip()
        _items = _items.rstrip(',')
        _items = _items.split(",")
        
        
        
        try:
            st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
        except :
            self.send_error(400, desc='invalid argument')
            return
        
        if not _pd:
            ed_time = datetime.datetime.now()
            delta = ed_time - st_time 
            _pd =  abs(delta.days)
        
        _pd = int(_pd)
        et_time = st_time + datetime.timedelta(days=_pd)
        st_datestr = st_time.strftime('%Y%m%d')
        et_datestr = et_time.strftime('%Y%m%d')
        
        all_data = []
        results = {}
        os_data = []
        days = []
        days_l = []
        for i in xrange(0,_pd):
            now = datetime.datetime.strptime(st_datestr,'%Y%m%d')
            delta = datetime.timedelta(days=i)  
            n_days = now + delta  
            days.append(n_days.strftime('%Y%m%d'))
            days_l.append({'days':n_days.strftime('%Y%m%d')})

        if _osid == "":
            xunhuan = [{'name':'All','id':'61,59,52'},{'name':'Android','id':'61'},{'name':'iOS','id':'52'},{'name':'WP7','id':'59'}]
        elif _device_type == "":
            xunhuan = [{'name':'All','id':'1,2'},{'name':'Phone','id':'1'},{'name':'Pad','id':'2'}]
        elif _pm == "":
            xunhuan = [{'name':'All','id':'1,3,2,8'},{'name':'qudao','id':'2,8'},{'name':'changshang','id':'1'}]
        else:
            xunhuan = [{'name':'All'}]
        
        db = connectMySQL.connMySQL_stat()
        c=db.cursor()
        fanhui = {}
        _table = "stat_day_total"
        for vxunhuan in xrange(len(xunhuan)):
            
            UV_list = []
            pv_list = []
            NU_list = []
            VV_list = []
            VVUV_list = []
            Dur_list = []
            DurVV_list = []
            DurUV_list = []
            Comp_list = []
            CompVV_list = []
            BefDurTime_list = []
            PlayDurTime_list = []
            PlayTimeVV_list = []
            PlayDurVV_list = []
            HDSDDurTime_list = []
            SDHDDurTime_list = []
            RelateAPIAveRespTime_list = []
            VdDetailAPIAveRespTime_list = []
            VdUrlAPIAveRespTime_list = []
            
            
            pv_all = 0
            UV_all = 0
            NU_all = 0
            VV_all = 0
            VVUV_all = 0
            Dur_all = 0
            DurVV_all = 0
            DurUV_all = 0
            Comp_all = 0
            CompVV_all = 0
                
            BefDurTime_all = 0
            PlayDurTime_all = 0
            PlayTimeVV_all = 0
            PlayDurVV_all = 0
            HDSDDurTime_all = 0
            SDHDDurTime_all = 0
            RelateAPIAveRespTime_all = 0
            VdDetailAPIAveRespTime_all = 0
            VdUrlAPIAveRespTime_all = 0
            for xy in xrange(len(days_l)):
                
                if _pm != "":
                    _pmsql = " and partner_mode in (%s) " % _pm
                else:
                    _pmsql = " "
                if _osid == "":
                    if _osid == "" and _device_type == "" and _pm == "":
                        sql = " SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server  FROM `%s` WHERE date = %s and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (1,2) and partner_mode in (1,2,3,8) " % (_table,days_l[xy]['days'],xunhuan[vxunhuan]['id'])
                        sql_apiresp = " SELECT apiresp FROM `%s` WHERE date = %s and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (1,2) and partner_mode in (1,2,3,8) " % (_table,days_l[xy]['days'],xunhuan[vxunhuan]['id'])
                    elif _osid == "" and _device_type != "":
                        sql = "SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server  FROM `%s` WHERE date = %s and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (%s) %s  " % (_table,days_l[xy]['days'],xunhuan[vxunhuan]['id'],_device_type,_pmsql)
                        sql_apiresp = "SELECT apiresp FROM `%s` WHERE date = %s and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (%s) %s  " % (_table,days_l[xy]['days'],xunhuan[vxunhuan]['id'],_device_type,_pmsql)
                    elif _osid == "" and _device_type == "":
                        sql = "SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server  FROM `%s` WHERE date = %s and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (1,2) %s  " % (_table,days_l[xy]['days'],xunhuan[vxunhuan]['id'],_pmsql)
                        sql_apiresp = "SELECT apiresp FROM `%s` WHERE date = %s and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (1,2) %s  " % (_table,days_l[xy]['days'],xunhuan[vxunhuan]['id'],_pmsql)
                elif _device_type == "":
                    sql = " SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server  FROM `%s` WHERE date = %s and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (%s) %s " % (_table,days_l[xy]['days'],_osid,xunhuan[vxunhuan]['id'],_pmsql)
                    sql_apiresp = " SELECT apiresp FROM `%s` WHERE date = %s and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (%s) %s " % (_table,days_l[xy]['days'],_osid,xunhuan[vxunhuan]['id'],_pmsql)
                elif _pm == "":
                    sql = " SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server  FROM `%s` WHERE date = %s and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (%s) " % (_table,days_l[xy]['days'],_osid,_device_type,xunhuan[vxunhuan]['id'])
                    sql_apiresp = " SELECT apiresp FROM `%s` WHERE date = %s and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (%s) " % (_table,days_l[xy]['days'],_osid,_device_type,xunhuan[vxunhuan]['id'])
                else:
                    sql = "SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server  FROM `%s` WHERE date = %s and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (%s) " % (_table,days_l[xy]['days'],_osid,_device_type,_pm)
                    sql_apiresp = "SELECT apiresp FROM `%s` WHERE date = %s and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (%s) " % (_table,days_l[xy]['days'],_osid,_device_type,_pm)
                
                #print sql
                c.execute(sql)  
                result = c.fetchall()
                if result[0][0] != None:
                    pv = int(result[0][3])
                    UV = int(result[0][4])
                    VV = int(result[0][5])
                    try:
                        VVUV = VV / UV
                    except:
                        VVUV = 0
                    Dur = int(result[0][10])
                    Dur = Dur / 60
                    try:
                        DurVV = Dur / VV
                    except:
                        DurVV = 0
                    try:
                        DurUV = Dur / UV
                    except:
                        DurUV = 0
                    DurVV = round(DurVV,2)
                    DurUV = round(DurUV,2)    
                    VVUV = round(VVUV,2)
                    Comp = int(result[0][11])
                    
                    NU = int(result[0][6])
                    pm = int(result[0][7])
                    
                    try:
                        CompVV = Comp / VV
                    except:
                        CompVV = 0
                    CompVV = round(CompVV,4)
                    
                    
                    before_duration = int(result[0][8])
                    before_times = int(result[0][9])
                    
                    if (before_duration == 0 or before_times == 0):
                        BefDurTime = 0
                    else:
                        BefDurTime = before_duration/before_times/1000
                    
                    BefDurTime = round(BefDurTime,2)
                    
                    play_load_duration = int(result[0][12])
                    play_load_times = int(result[0][13])
                    
                    if (play_load_duration == 0 or play_load_times == 0):
                        PlayDurTime = 0
                    else:
                        PlayDurTime = play_load_duration/play_load_times/1000
                    
                    PlayDurTime = round(PlayDurTime,2)
                    
                    if (play_load_times == 0 or VV == 0):
                        PlayTimeVV = 0
                    else:
                        PlayTimeVV = play_load_times/VV/1000
                    
                    PlayTimeVV = round(PlayTimeVV,2)
                    
                    if (play_load_duration == 0 or VV == 0):
                        PlayDurVV = 0
                    else:
                        PlayDurVV = play_load_duration/VV/1000
                    
                    PlayDurVV = round(PlayDurVV,2)
                    play_hdsd_times = int(result[0][14])
                    play_hdsd_duration = int(result[0][15])
                    
                    if (play_hdsd_duration == 0 or play_hdsd_times == 0):
                        HDSDDurTime = 0
                    else:
                        HDSDDurTime = play_hdsd_duration/play_hdsd_times/1000
                    
                    HDSDDurTime = round(HDSDDurTime,2)
                    
                    play_sdhd_times = int(result[0][16])
                    play_sdhd_duration = int(result[0][17])
                    
                    if (play_sdhd_duration == 0 or play_sdhd_times == 0):
                        SDHDDurTime = 0
                    else:
                        SDHDDurTime = play_sdhd_times/play_sdhd_times/1000
                    
                    SDHDDurTime = round(SDHDDurTime,2)
                    
                    play_resptime,play_times,draw_resptime,draw_times,getVideoDetail_resptime,getVideoDetail_times = clientcache.getJsondata_new(sql_apiresp)
                    
                    
                    if (draw_resptime == 0 or draw_times == 0):
                        RelateAPIAveRespTime = 0
                    else:
                        RelateAPIAveRespTime = draw_resptime/draw_times/1000
                    
                    RelateAPIAveRespTime = round(RelateAPIAveRespTime,2)
                    
                    if (getVideoDetail_resptime == 0 or getVideoDetail_times == 0):
                        VdDetailAPIAveRespTime = 0
                    else:
                        VdDetailAPIAveRespTime = getVideoDetail_resptime/getVideoDetail_times/1000
                    
                    VdDetailAPIAveRespTime = round(VdDetailAPIAveRespTime,2)
                    if (play_resptime == 0 or play_times == 0):
                        VdUrlAPIAveRespTime = 0
                    else:
                        VdUrlAPIAveRespTime = play_resptime/play_times/1000
                    
                    VdUrlAPIAveRespTime = round(VdUrlAPIAveRespTime,2)                    
                else:
                    pv = 0
                    UV = 0
                    VV = 0
                    try:
                        VVUV = VV / UV
                    except:
                        VVUV = 0
                    Dur = 0
                    try:
                        DurVV = Dur / VV
                    except:
                        DurVV = 0
                    try:
                        DurUV = Dur / UV
                    except:
                        DurUV = 0
                    DurVV = round(DurVV,2)
                    DurUV = round(DurUV,2)    
                    VVUV = round(VVUV,2)
                    
                    
                    
                    Comp = 0
                    
                    NU = 0
                    pm = 0
                    
                    try:
                        CompVV = Comp / VV
                    except:
                        CompVV = 0
                    CompVV = round(CompVV,2)
                    
                    before_duration = 0
                    before_times = 0
                    
                    if (before_duration == 0 or before_times == 0):
                        BefDurTime = 0
                    else:
                        BefDurTime = before_duration/before_times/1000
                    
                    BefDurTime = round(BefDurTime,2)
                    
                    play_load_duration = 0
                    play_load_times = 0
                    
                    if (play_load_duration == 0 or play_load_times == 0):
                        PlayDurTime = 0
                    else:
                        PlayDurTime = play_load_duration/play_load_times/1000
                    
                    PlayDurTime = round(PlayDurTime,2)
                    
                    if (play_load_times == 0 or VV == 0):
                        PlayTimeVV = 0
                    else:
                        PlayTimeVV = play_load_times/VV/1000
                    
                    PlayTimeVV = round(PlayTimeVV,2)
                    
                    if (play_load_duration == 0 or VV == 0):
                        PlayDurVV = 0
                    else:
                        PlayDurVV = play_load_duration/VV/1000
                    
                    PlayDurVV = round(PlayDurVV,2)
                    
                    
                    play_hdsd_times = 0
                    play_hdsd_duration = 0
                    
                    if (play_hdsd_duration == 0 or play_hdsd_times == 0):
                        HDSDDurTime = 0
                    else:
                        HDSDDurTime = play_hdsd_duration/play_hdsd_times/1000
                    
                    HDSDDurTime = round(HDSDDurTime,2)
                    
                    play_sdhd_times = 0
                    play_sdhd_duration = 0
                    
                    if (play_sdhd_duration == 0 or play_sdhd_times == 0):
                        SDHDDurTime = 0
                    else:
                        SDHDDurTime = play_sdhd_times/play_sdhd_times/1000
                    
                    SDHDDurTime = round(SDHDDurTime,2)
                    
                    play_resptime,play_times,draw_resptime,draw_times,getVideoDetail_resptime,getVideoDetail_times = clientcache.getJsondata_new(sql_apiresp)
                                        
                    if (draw_resptime == 0 or draw_times == 0):
                        RelateAPIAveRespTime = 0
                    else:
                        RelateAPIAveRespTime = draw_resptime/draw_times/1000
                    
                    RelateAPIAveRespTime = round(RelateAPIAveRespTime,2)
                    
                    if (getVideoDetail_resptime == 0 or getVideoDetail_times == 0):
                        VdDetailAPIAveRespTime = 0
                    else:
                        VdDetailAPIAveRespTime = getVideoDetail_resptime/getVideoDetail_times/1000
                    
                    VdDetailAPIAveRespTime = round(VdDetailAPIAveRespTime,2)
                    
                    if (play_resptime == 0 or play_times == 0):
                        VdUrlAPIAveRespTime = 0
                    else:
                        VdUrlAPIAveRespTime = play_resptime/play_times/1000
                    
                    VdUrlAPIAveRespTime = round(VdUrlAPIAveRespTime,2)
                
                
                
                UV_list.append(str(UV))
                pv_list.append(str(pv))
                NU_list.append(str(NU))
                VV_list.append(str(VV))
                VVUV_list.append(str(VVUV))
                Dur_list.append(str(Dur))
                DurVV_list.append(str(DurVV))
                DurUV_list.append(str(DurUV))
                Comp_list.append(str(Comp))
                CompVV_list.append(str(CompVV))
                BefDurTime_list.append(str(BefDurTime))
                PlayDurTime_list.append(str(PlayDurTime))
                PlayTimeVV_list.append(str(PlayTimeVV))
                PlayDurVV_list.append(str(PlayDurVV))
                HDSDDurTime_list.append(str(HDSDDurTime))
                SDHDDurTime_list.append(str(SDHDDurTime))
                RelateAPIAveRespTime_list.append(str(RelateAPIAveRespTime))
                VdDetailAPIAveRespTime_list.append(str(VdDetailAPIAveRespTime))
                VdUrlAPIAveRespTime_list.append(str(VdUrlAPIAveRespTime))

                
                days_l[xy]['pv'] = pv
                days_l[xy]['UV'] = UV
                days_l[xy]['VV'] = VV
                days_l[xy]['NU'] = NU
                days_l[xy]['VVUV'] = VVUV
                days_l[xy]['Dur'] = Dur
                days_l[xy]['DurVV'] = DurVV
                days_l[xy]['DurUV'] = DurUV
                days_l[xy]['Comp'] = Comp
                days_l[xy]['CompVV'] = CompVV
    
                days_l[xy]['BefDurTime'] = BefDurTime
                days_l[xy]['PlayDurTime'] = PlayDurTime
                days_l[xy]['PlayTimeVV'] = PlayTimeVV
                days_l[xy]['PlayDurVV'] = PlayDurVV
                days_l[xy]['HDSDDurTime'] = HDSDDurTime
                days_l[xy]['SDHDDurTime'] = SDHDDurTime
                days_l[xy]['RelateAPIAveRespTime'] = RelateAPIAveRespTime
                days_l[xy]['VdDetailAPIAveRespTime'] = VdDetailAPIAveRespTime
                days_l[xy]['VdUrlAPIAveRespTime'] = VdUrlAPIAveRespTime
                
                pv_all += pv
                UV_all += UV
                NU_all += NU
                VV_all += VV
                VVUV_all += VVUV
                Dur_all += Dur
                DurVV_all += DurVV
                DurUV_all += DurUV
                Comp_all += Comp
                CompVV_all += CompVV
                
                BefDurTime_all += BefDurTime
                PlayDurTime_all += PlayDurTime
                PlayTimeVV_all += PlayTimeVV
                PlayDurVV_all += PlayDurVV
                HDSDDurTime_all += HDSDDurTime
                SDHDDurTime_all += SDHDDurTime
                RelateAPIAveRespTime_all += RelateAPIAveRespTime
                VdDetailAPIAveRespTime_all += VdDetailAPIAveRespTime
                VdUrlAPIAveRespTime_all += VdUrlAPIAveRespTime_all
            
            #print eval("%s%s" % ('UV','_all'))
            
            #生成线性图
            xianx = "["
            
            for xy in xrange(len(days_l)):
                yy = days_l[xy]['days'][0:4]
                mm = days_l[xy]['days'][4:6]
                dd = days_l[xy]['days'][6:]
                xianx += "'%s-%s'," % (mm,dd)
            xianx += "]" 
            
            xiany = "["
            for items_value in _items:
                shuzu = eval("%s%s" % (items_value,'_list'))
                shuzu_str = ",".join(shuzu)
                qiangzu = []
                qiangzu.append(items_value)
                mingzi = cnsort.valueFullNameArr(qiangzu)
                xiany += "{name: '%s',data: [%s]}," % (mingzi[0],shuzu_str)            
            xiany += "]"                
            #print xianx
            #生成表格
            table = ""
            for xy in xrange(len(days_l)):
                if xy % 2 ==0:
                    bg = " class='new_silver_even' "
                else:
                    bg = " class='new_silver_odd' "
                table += "<tr %s><td>%s</td>" % (bg,days_l[xy]['days'])
                
                for items_value in _items:
                    table += cnsort.genTableResultInc3(days_l[xy-1].get(items_value),days_l[xy].get(items_value),items_value,xy)
                table +="</tr>"
            #生成合计
            table += u"</tbody><tfoot><tr><th class='new_silver_first_n footer'>合计</th>"
            for items_value in _items:
                    if cnsort.checkValueMode(items_value):
                        shu = eval("%s%s" % (items_value,'_all'))
                        
                        if items_value == "CompVV":
                            shu = shu / len(days_l)
                            table += "<th>%s%%</th>" % (shu*100)
                        else:
                            shu = shu / len(days_l)
                            shu = round(shu,2)
                            table += "<th>%s</th>" % shu
                    else:
                        shu = eval("%s%s" % (items_value,'_all'))
                        table += "<th>%s</th>" % cnsort.num2money(shu)
            
            table += "</tr></tfoot></table></div>"
            
            zongzong = {}
            
            zongzong['pv_all'] = pv_all
            zongzong['UV_all'] = UV_all
            zongzong['VV_all'] = VV_all
            zongzong['NU_all'] = NU_all
            zongzong['VVUV_all'] = VVUV_all
            zongzong['Dur_all'] = Dur_all
            zongzong['DurVV_all'] = DurVV_all
            zongzong['DurUV_all'] = DurUV_all
            zongzong['Comp_all'] = Comp_all
            zongzong['CompVV_all'] = CompVV_all
                
            zongzong['BefDurTime_all'] = BefDurTime_all
            zongzong['PlayDurTime_all'] = PlayDurTime_all
            zongzong['PlayTimeVV_all'] = PlayTimeVV_all
            zongzong['PlayDurVV_all'] = PlayDurVV_all
            zongzong['HDSDDurTime_all'] = HDSDDurTime_all
            zongzong['SDHDDurTime_all'] = SDHDDurTime_all
            zongzong['RelateAPIAveRespTime_all'] = RelateAPIAveRespTime_all
            zongzong['VdDetailAPIAveRespTime_all'] = VdDetailAPIAveRespTime_all
            zongzong['VdUrlAPIAveRespTime_all'] = VdUrlAPIAveRespTime_all
            
            fv = {}
            
            fv['table'] = table
            fv['zongzong'] = zongzong
            fv['xianx'] = xianx
            fv['xiany'] = xiany
            
            fanhui[xunhuan[vxunhuan]['name']] = fv
            
        #生成饼图
        blist = ['UV','VV','NU','Comp','Dur']
        if _osid == "":
            fc = {}
            for blist_value in blist:
                kvalue = "%s%s" % (blist_value,'_all')
                _android = fanhui['Android']['zongzong'][kvalue]
                _ios = fanhui['iOS']['zongzong'][kvalue]
                _wp7 = fanhui['WP7']['zongzong'][kvalue]
                dd = "[['Android',%s],['Ios',%s],['WP7',%s]]" % (_android,_ios,_wp7)
                fc[blist_value] = dd 
        elif _device_type == "":
            fc = {}
            for blist_value in blist:
                kvalue = "%s%s" % (blist_value,'_all')
                _phone = fanhui['Phone']['zongzong'][kvalue]
                _pad = fanhui['Pad']['zongzong'][kvalue]
                dd = "[['Phone',%s],['Pad',%s]]" % (_phone,_pad)
                fc[blist_value] = dd 
        elif _pm == "":
            fc = {}
            for blist_value in blist:
                kvalue = "%s%s" % (blist_value,'_all')
                _changshang = fanhui['changshang']['zongzong'][kvalue]
                _qudao = fanhui['qudao']['zongzong'][kvalue]
                dd = u"[['厂商内置',%s],['渠道推广',%s]]" % (_changshang,_qudao)
                fc[blist_value] = dd
        else:
            fc = '123'
        fanhui['All']['bingtu'] = fc
            
        c.close()
        db.close()
        self.write(fanhui)
        self.finish()


class CheckFinished(BaseHandler):
    
    def get(self):
        '''
        _yesday = datetime.datetime.today() + datetime.timedelta(-1)
        _date = _yesday.strftime('%Y%m%d')
        print _date
        _result = os.path.isfile("/tmp/%s.notfinished" % _date)
        
        if _result == True:
            _back = "0"
        else:
            _back = "1"
        '''
        import glob
        listss = glob.glob('/tmp/*.notfinished')
        if len(listss) != 0:
            chcc = listss[0]
            chcs = chcc.replace("/tmp/","").replace(".notfinished","")
            ccdate = datetime.datetime.strptime(chcs,'%Y%m%d')
            et_time = ccdate + datetime.timedelta(-1)
            st_datestr = et_time.strftime('%Y%m%d')
            _back = st_datestr
        else:
            _back = "1"
        
        self.write(_back)
        self.finish()

class NewMainVideo_bf(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        _pm = self.get_argument('pm','').strip()
        _items = self.get_argument('items','UV,VV,').strip()
        _items = _items.rstrip(',')
        _items = _items.split(",")
        
        """
        AboutDiv = ""
        for _it in _items:
            if _it in common.AboutVideo:
                AboutDiv += common.AboutVideo[_it]
        """
        
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        m_value = mc.get(_md5.hexdigest()) or {}
        
        #print settings.cache_on
        if settings.cache_on == 0:
            m_value = {}
            #print '123'
        
        
        if not m_value:
            
            try:
                st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                return
            
            if not _pd:
                ed_time = datetime.datetime.now()
                delta = ed_time - st_time 
                _pd =  abs(delta.days)
            
            _pd = int(_pd)
            et_time = st_time + datetime.timedelta(days=_pd)
            st_datestr = st_time.strftime('%Y%m%d')
            et_datestr = et_time.strftime('%Y%m%d')
            
            all_data = []
            results = {}
            os_data = []
            days = []
            for i in xrange(0,_pd):
                now = datetime.datetime.strptime(st_datestr,'%Y%m%d')
                delta = datetime.timedelta(days=i)  
                n_days = now + delta  
                days.append(n_days.strftime('%Y%m%d'))
            
            _table = "stat_day_total"
            
            sql_bdur_new = "  select sum(num),date,time_type,os_id,device_type,partner_mode from stat_duration_result where duration_type = 1 and date >= %s and date < %s  and  pid_stat=1 and os_id in (61,52,59) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and device_type in (1,2) and partner_mode in (1,2,3,8)  group by date,time_type " % (st_datestr,et_datestr)
            
            if _osid == "":
                xunhuan = [{'name':'All','id':'61,59,52'},{'name':'Android','id':'61'},{'name':'iOS','id':'52'},{'name':'WP7','id':'59'}]
                
                sql_new = " SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server,sum(play_hd_times),sum(play_hd_duration),sum(play_sd_times),sum(play_sd_duration),sum(play_hd2_times),sum(play_hd2_duration)   FROM `%s` WHERE date >= %s and date < %s  and  business_type=2 and pid_stat=1 and os_id in (61,52,59) and device_type in (1,2) and partner_mode in (1,2,3,8) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' group by date,os_id,partner_mode,device_type " % (_table,st_datestr,et_datestr)
                
                
                
                
                
            elif _device_type == "":
                xunhuan = [{'name':'All','id':'1,2'},{'name':'Phone','id':'1'},{'name':'Pad','id':'2'}]
                
                sql_new = " SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server,sum(play_hd_times),sum(play_hd_duration),sum(play_sd_times),sum(play_sd_duration),sum(play_hd2_times),sum(play_hd2_duration)   FROM `%s` WHERE date >= %s and date < %s  and  business_type=2 and pid_stat=1 and os_id in (61,52,59) and device_type in (1,2) and partner_mode in (1,2,3,8) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' group by date,device_type " % (_table,st_datestr,et_datestr)
                
                
            elif _pm == "":
                xunhuan = [{'name':'All','id':'1,3,2,8'},{'name':'qudao','id':'2,8'},{'name':'changshang','id':'1'}]
                
                sql_new = " SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server,sum(play_hd_times),sum(play_hd_duration),sum(play_sd_times),sum(play_sd_duration),sum(play_hd2_times),sum(play_hd2_duration)   FROM `%s` WHERE date >= %s and date < %s  and  business_type=2 and pid_stat=1 and os_id in (61,52,59) and device_type in (1,2) and partner_mode in (1,2,3,8) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' group by date,partner_mode " % (_table,st_datestr,et_datestr)
                
            else:
                xunhuan = [{'name':'All'}]
                
                sql_new = " SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server,sum(play_hd_times),sum(play_hd_duration),sum(play_sd_times),sum(play_sd_duration),sum(play_hd2_times),sum(play_hd2_duration)   FROM `%s` WHERE date >= %s and date < %s  and  business_type=2 and pid_stat=1 and os_id in (61,52,59) and device_type in (1,2) and partner_mode in (1,2,3,8) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' group by date " % (_table,st_datestr,et_datestr)
            
            db = connectMySQL.connMySQL_stat()
            c=db.cursor()
            
            print sql_new
            c.execute(sql_new)  
            result_new = c.fetchall()
            c.execute(sql_bdur_new)
            result_bdur_new = c.fetchall()
            
            
            fanhui = {}
            
            for vxunhuan in xrange(len(xunhuan)):
                
                result_all = []
                result_bdur = []
                
                if _pm != "":
                    _pmsql = " and partner_mode in (%s) " % _pm
                else:
                    _pmsql = " "
                tihuanriqi = "tihuanriqi"
                
                xunhuanlow = str(xunhuan[vxunhuan]['id']).split(',')
                print xunhuanlow
                
                
                if _osid == "":
                    if _osid == "" and _device_type == "" and _pm == "":
                        
                        for rnew in result_new:
                            if str(rnew[1]) in xunhuanlow and (str(rnew[2]) == "1" or str(rnew[2]) == "2") and (str(rnew[7]) == "1" or str(rnew[2]) == "2" or str(rnew[2]) == "3" or str(rnew[2]) == "8"):
                                zhanshi = [rnew[0],rnew[1],rnew[2],rnew[3],rnew[4],rnew[5],rnew[6],rnew[7],rnew[8],rnew[9],rnew[10],rnew[11],rnew[12],rnew[13],rnew[14],rnew[15],rnew[16],rnew[17],rnew[18],rnew[19],rnew[20],rnew[21],rnew[22],rnew[23],rnew[24],rnew[25]]
                                result_all.append(zhanshi)
                        
                        for rnew in result_bdur_new:
                            if str(rnew[3]) in xunhuanlow and (str(rnew[4]) == "1" or str(rnew[4]) == "2") and (str(rnew[5]) == "1" or str(rnew[5]) == "2" or str(rnew[5]) == "3" or str(rnew[5]) == "8"):
                                zhanshi = [rnew[0],rnew[1],rnew[2],rnew[3],rnew[4],rnew[5]]
                                result_bdur.append(zhanshi)
                            
                        
                        sql = " SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server,sum(play_hd_times),sum(play_hd_duration),sum(play_sd_times),sum(play_sd_duration),sum(play_hd2_times),sum(play_hd2_duration)   FROM `%s` WHERE date >= %s and date < %s  and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (1,2) and partner_mode in (1,2,3,8) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' group by date " % (_table,st_datestr,et_datestr,xunhuan[vxunhuan]['id'])
                        sql_apiresp = " SELECT apiresp FROM `%s` WHERE date = %s and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (1,2) and partner_mode in (1,2,3,8) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and apiresp != '' " % (_table,tihuanriqi,xunhuan[vxunhuan]['id'])
                        
                        sql_bdur = "  select sum(num),date,time_type from stat_duration_result where duration_type = 1 and date >= %s and date < %s  and  pid_stat=1 and os_id in (%s) and device_type in (1,2) and partner_mode in (1,2,3,8) and ver = 'ALL' and prov = 'ALL' and city = 'ALL'   group by date,time_type " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'])
                        
                    elif _osid == "" and _device_type != "":
                        sql = "SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server,sum(play_hd_times),sum(play_hd_duration),sum(play_sd_times),sum(play_sd_duration),sum(play_hd2_times),sum(play_hd2_duration)  FROM `%s` WHERE date >= %s and date < %s and  business_type=2 and pid_stat=1 and os_id in (%s) and  ver = 'ALL' and prov = 'ALL' and city = 'ALL'  and device_type in (%s) %s  group by date " % (_table,st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type,_pmsql)
                        sql_apiresp = "SELECT apiresp FROM `%s` WHERE date = %s and  business_type=2 and pid_stat=1 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and apiresp != ''  and device_type in (%s) %s  " % (_table,tihuanriqi,xunhuan[vxunhuan]['id'],_device_type,_pmsql)
                        
                        sql_bdur = "  select sum(num),date,time_type from stat_duration_result where duration_type = 1 and date >= %s and date < %s  and  pid_stat=1 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and device_type in (%s) %s  group by date,time_type " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type,_pmsql)
                        
                    elif _osid == "" and _device_type == "":
                        sql = "SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server,sum(play_hd_times),sum(play_hd_duration),sum(play_sd_times),sum(play_sd_duration),sum(play_hd2_times),sum(play_hd2_duration)  FROM `%s` WHERE date >= %s and date < %s and  business_type=2 and pid_stat=1 and os_id in (%s) and ver = 'ALL'   and prov = 'ALL' and city = 'ALL'   and device_type in (1,2) %s  group by date " % (_table,st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_pmsql)
                        sql_apiresp = "SELECT apiresp FROM `%s` WHERE date = %s and  business_type=2 and pid_stat=1 and os_id in (%s) and ver = 'ALL'  and prov = 'ALL' and city = 'ALL' and apiresp != '' and device_type in (1,2) %s  " % (_table,tihuanriqi,xunhuan[vxunhuan]['id'],_pmsql)
                        
                        
                        sql_bdur = "  select sum(num),date,time_type from stat_duration_result where duration_type = 1 and date >= %s and date < %s  and  pid_stat=1 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and device_type in (1,2) %s  group by date,time_type " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_pmsql)
                        
                elif _device_type == "":
                        sql = " SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server,sum(play_hd_times),sum(play_hd_duration),sum(play_sd_times),sum(play_sd_duration),sum(play_hd2_times),sum(play_hd2_duration)  FROM `%s` WHERE date >= %s and date < %s and  business_type=2 and pid_stat=1 and os_id in (%s) and ver = 'ALL'   and prov = 'ALL' and city = 'ALL'    and device_type in (%s) %s  group by date" % (_table,st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'],_pmsql)
                        sql_apiresp = " SELECT apiresp FROM `%s` WHERE date = %s and  business_type=2 and pid_stat=1 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and apiresp != '' and  device_type in (%s) %s " % (_table,tihuanriqi,_osid,xunhuan[vxunhuan]['id'],_pmsql)
                        
                        
                        sql_bdur = "  select sum(num),date,time_type from stat_duration_result where duration_type = 1 and date >= %s and date < %s  and  pid_stat=1 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and device_type in (%s) %s  group by date,time_type " % (st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'],_pmsql)
                        
                elif _pm == "":
                        sql = " SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server,sum(play_hd_times),sum(play_hd_duration),sum(play_sd_times),sum(play_sd_duration),sum(play_hd2_times),sum(play_hd2_duration)  FROM `%s` WHERE date >= %s and date < %s and  business_type=2 and pid_stat=1 and os_id in (%s) and ver = 'ALL'   and prov = 'ALL' and city = 'ALL'   and  device_type in (%s) and partner_mode in (%s)   group by date " % (_table,st_datestr,et_datestr,_osid,_device_type,xunhuan[vxunhuan]['id'])
                        sql_apiresp = " SELECT apiresp FROM `%s` WHERE date = %s and  business_type=2 and pid_stat=1 and os_id in (%s) and ver = 'ALL'   and prov = 'ALL' and city = 'ALL'  and  device_type in (%s) and partner_mode in (%s) and apiresp != '' " % (_table,tihuanriqi,_osid,_device_type,xunhuan[vxunhuan]['id'])
                        
                        sql_bdur = "  select sum(num),date,time_type from stat_duration_result where duration_type = 1 and date >= %s and date < %s  and  pid_stat=1 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and  device_type in (%s) and partner_mode in (%s)  group by date,time_type " % (st_datestr,et_datestr,_osid,_device_type,xunhuan[vxunhuan]['id'])
                        
                else:
                        sql = "SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server,sum(play_hd_times),sum(play_hd_duration),sum(play_sd_times),sum(play_sd_duration),sum(play_hd2_times),sum(play_hd2_duration)  FROM `%s` WHERE date >= %s and date < %s and  business_type=2 and pid_stat=1 and os_id in (%s) and ver = 'ALL'   and prov = 'ALL' and city = 'ALL'    and   device_type in (%s) and partner_mode in (%s)   group by date " % (_table,st_datestr,et_datestr,_osid,_device_type,_pm)
                        sql_apiresp = "SELECT apiresp FROM `%s` WHERE date = %s and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (%s) and ver = 'ALL'  and prov = 'ALL' and city = 'ALL' and   partner_mode in (%s) and apiresp != '' " % (_table,tihuanriqi,_osid,_device_type,_pm)
                        
                        sql_bdur = "  select sum(num),date,time_type from stat_duration_result where duration_type = 1 and date >= %s and date < %s  and  pid_stat=1 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and   device_type in (%s) and partner_mode in (%s)  group by date,time_type " % (st_datestr,et_datestr,_osid,_device_type,_pm)
                        
                '''        
                print sql
                c.execute(sql)  
                result_all = c.fetchall()
                #print sql_bdur
                c.execute(sql_bdur)
                result_bdur = c.fetchall()
                '''
                
                UV_list = []
                pv_list = []
                NU_list = []
                VV_list = []
                VVUV_list = []
                Dur_list = []
                DurVV_list = []
                DurUV_list = []
                Comp_list = []
                CompVV_list = []
                BefDurTime_list = []
                PlayDurTime_list = []
                PlayTimeVV_list = []
                PlayDurVV_list = []
                HDSDDurTime_list = []
                SDHDDurTime_list = []
                HD2DurTime_list = []
                RelateAPIAveRespTime_list = []
                VdDetailAPIAveRespTime_list = []
                VdUrlAPIAveRespTime_list = []
                
                
                b3_all = 0
                b5_all = 0
                b8_all = 0
                b300_all = 0
                b301_all = 0
                
                pv_all = 0
                UV_all = 0
                NU_all = 0
                VV_all = 0
                VVUV_all = 0
                Dur_all = 0
                DurVV_all = 0
                DurUV_all = 0
                Comp_all = 0
                CompVV_all = 0
                    
                BefDurTime_all = 0
                PlayDurTime_all = 0
                PlayTimeVV_all = 0
                PlayDurVV_all = 0
                HDSDDurTime_all = 0
                SDHDDurTime_all = 0
                HD2DurTime_all = 0
                RelateAPIAveRespTime_all = 0
                VdDetailAPIAveRespTime_all = 0
                VdUrlAPIAveRespTime_all = 0
                
                days_l = []
                jiriqi = []
                for result in result_all:
                    jiriqi.append(str(result[0]))
                
                
                jcjishu = 0
                for result in result_all:
                    
                    _riqi = str(result[0])
                    
                    b3 = 0
                    b5 = 0
                    b8 = 0
                    b300 = 0
                    b301 = 0
                    
                    for bdurv in result_bdur:
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 3:
                            b3 = int(bdurv[0])
                        
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 5:
                            b5 = int(bdurv[0])
                            
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 8:
                            b8 = int(bdurv[0])
                            
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 300:
                            b300 = int(bdurv[0])
                        
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 301:
                            b301 = int(bdurv[0])
                    
                    
                    pv = int(result[3])
                    UV = int(result[4])
                    VV = int(result[5])
                    try:
                        VVUV = VV / UV
                    except:
                        VVUV = 0
                    Dur = int(result[10])
                    Dur = Dur / 60
                    try:
                        DurVV = Dur / VV
                    except:
                        DurVV = 0
                    try:
                        DurUV = Dur / UV
                    except:
                        DurUV = 0
                    DurVV = round(DurVV,2)
                    DurUV = round(DurUV,2)    
                    VVUV = round(VVUV,2)
                    Comp = int(result[11])
                        
                    NU = int(result[6])
                    pm = int(result[7])
                        
                    try:
                        CompVV = Comp / VV
                    except:
                        CompVV = 0
                    CompVV = round(CompVV,4)
                        
                        
                    before_duration = int(result[8])
                    before_times = int(result[9])
                    
                    #print before_duration,before_times
                        
                    if (before_duration == 0 or before_times == 0):
                        BefDurTime = 0
                    else:
                        BefDurTime = before_duration/before_times/1000
                        
                    BefDurTime = round(BefDurTime,2)
                        
                    play_load_duration = int(result[12])
                    play_load_times = int(result[13])
                        
                    if (play_load_duration == 0 or play_load_times == 0):
                        PlayDurTime = 0
                    else:
                        PlayDurTime = play_load_duration/play_load_times/1000
                        
                    PlayDurTime = round(PlayDurTime,2)
                        
                    if (play_load_times == 0 or VV == 0):
                        PlayTimeVV = 0
                    else:
                        PlayTimeVV = play_load_times/VV
                        
                    PlayTimeVV = round(PlayTimeVV,2)
                        
                    if (play_load_duration == 0 or VV == 0):
                        PlayDurVV = 0
                    else:
                        PlayDurVV = play_load_duration/VV/1000
                        
                    
                    play_hd_times = int(result[20])

                    play_hd_duration = int(result[21])

                    play_sd_times = int(result[22])

                    play_sd_duration = int(result[23])

                    play_hd2_times = int(result[24])

                    play_hd2_duration = int(result[25])

                        
                    PlayDurVV = round(PlayDurVV,2)
                    play_hdsd_times = int(result[14])
                    play_hdsd_duration = int(result[15])
                    
                    play_hdsd_durationhe = play_sd_duration + play_hdsd_duration
                    play_hdsd_timeshe = play_sd_times + play_hdsd_times
                    
                        
                    if (play_hdsd_durationhe == 0 or play_hdsd_timeshe == 0):
                        HDSDDurTime = 0
                    else:
                        HDSDDurTime = play_hdsd_durationhe/play_hdsd_timeshe/1000
                        
                    HDSDDurTime = round(HDSDDurTime,2)
                        
                    play_sdhd_times = int(result[16])
                    play_sdhd_duration = int(result[17])
                    
                    
                    play_sdhd_durationhe = play_sd_duration + play_sdhd_duration
                    play_sdhd_timeshe = play_sd_times + play_sdhd_times
                        
                    if (play_sdhd_durationhe == 0 or play_sdhd_timeshe == 0):
                        SDHDDurTime = 0
                    else:
                        SDHDDurTime = play_sdhd_durationhe/play_sdhd_timeshe/1000
                    
                    SDHDDurTime = round(SDHDDurTime,2)
                        
                        
                    if (play_hd2_duration == 0 or play_hd2_times == 0):
                        HD2DurTime = 0
                    else:
                        HD2DurTime = play_hd2_duration/play_hd2_times/1000
                        
                    HD2DurTime = round(HD2DurTime,2)
                    
                    
                    
                    if jcjishu == 0:
                        sql_apiresp = sql_apiresp.replace("tihuanriqi",str(result[0]))
                    else:
                        sql_apiresp = sql_apiresp.replace(jiriqi[jcjishu-1],str(result[0]))
                    
                    
                    
                    cha = 0
                    xuyao_ziduan = ['RelateAPIAveRespTime','VdDetailAPIAveRespTime','VdUrlAPIAveRespTime']
    
                    cha = len(set(_items) & set(xuyao_ziduan))
                    
                    
                    if cha != 0:
                        play_resptime,play_times,draw_resptime,draw_times,getVideoDetail_resptime,getVideoDetail_times = clientcache.getJsondata_new(sql_apiresp)
                    else:
                        play_resptime = 0
                        play_times = 0
                        draw_resptime = 0
                        draw_times = 0
                        getVideoDetail_resptime = 0
                        getVideoDetail_times = 0
                        
                    if (draw_resptime == 0 or draw_times == 0):
                        RelateAPIAveRespTime = 0
                    else:
                        RelateAPIAveRespTime = draw_resptime/draw_times/1000
                        
                    RelateAPIAveRespTime = round(RelateAPIAveRespTime,2)
                        
                    if (getVideoDetail_resptime == 0 or getVideoDetail_times == 0):
                        VdDetailAPIAveRespTime = 0
                    else:
                        VdDetailAPIAveRespTime = getVideoDetail_resptime/getVideoDetail_times/1000
                        
                    VdDetailAPIAveRespTime = round(VdDetailAPIAveRespTime,2)
                    if (play_resptime == 0 or play_times == 0):
                        VdUrlAPIAveRespTime = 0
                    else:
                        VdUrlAPIAveRespTime = play_resptime/play_times/1000
                        
                    VdUrlAPIAveRespTime = round(VdUrlAPIAveRespTime,2)                    
                    
                        
                    
                    
                    
                    UV_list.append(str(UV))
                    pv_list.append(str(pv))
                    NU_list.append(str(NU))
                    VV_list.append(str(VV))
                    VVUV_list.append(str(VVUV))
                    Dur_list.append(str(Dur))
                    DurVV_list.append(str(DurVV))
                    DurUV_list.append(str(DurUV))
                    Comp_list.append(str(Comp))
                    CompVV_list.append(str(CompVV))
                    BefDurTime_list.append(str(BefDurTime))
                    PlayDurTime_list.append(str(PlayDurTime))
                    PlayTimeVV_list.append(str(PlayTimeVV))
                    PlayDurVV_list.append(str(PlayDurVV))
                    HDSDDurTime_list.append(str(HDSDDurTime))
                    HD2DurTime_list.append(str(HD2DurTime))
                    SDHDDurTime_list.append(str(SDHDDurTime))
                    RelateAPIAveRespTime_list.append(str(RelateAPIAveRespTime))
                    VdDetailAPIAveRespTime_list.append(str(VdDetailAPIAveRespTime))
                    VdUrlAPIAveRespTime_list.append(str(VdUrlAPIAveRespTime))
                    
                    bdurtime = {}
                    
                    bdurtime['pingjun'] = BefDurTime
                    
                    bdurtime['b3'] = b3
                    bdurtime['b5'] = b5
                    bdurtime['b8'] = b8
                    bdurtime['b300'] = b300
                    bdurtime['b301'] = b301
                    bdurtime['zong'] = int(result[9])
                    

                    
                    days_l.append({'days':_riqi,'pv':pv,'UV':UV,'VV':VV,'NU':NU,'VVUV':VVUV,'Dur':Dur,'DurVV':DurVV,'DurUV':DurUV,'Comp':Comp,'CompVV':CompVV,'BefDurTime':BefDurTime,'PlayDurTime':PlayDurTime,'PlayTimeVV':PlayTimeVV,'HDSDDurTime':HDSDDurTime,'SDHDDurTime':SDHDDurTime,'HD2DurTime':HD2DurTime,'RelateAPIAveRespTime':RelateAPIAveRespTime,'VdDetailAPIAveRespTime':VdDetailAPIAveRespTime,'VdUrlAPIAveRespTime':VdUrlAPIAveRespTime,'PlayDurVV':PlayDurVV,'bdurtime':bdurtime})
                    
                    
                    
                    b3_all += b3
                    b5_all += b5
                    b8_all += b8
                    b300_all += b300
                    b301_all += b301
                    
                    
                    pv_all += pv
                    UV_all += UV
                    NU_all += NU
                    VV_all += VV
                    VVUV_all += VVUV
                    Dur_all += Dur
                    DurVV_all += DurVV
                    DurUV_all += DurUV
                    Comp_all += Comp
                    CompVV_all += CompVV
                    
                    BefDurTime_all += BefDurTime
                    PlayDurTime_all += PlayDurTime
                    PlayTimeVV_all += PlayTimeVV
                    PlayDurVV_all += PlayDurVV
                    HDSDDurTime_all += HDSDDurTime
                    SDHDDurTime_all += SDHDDurTime
                    HD2DurTime_all += HD2DurTime
                    RelateAPIAveRespTime_all += RelateAPIAveRespTime
                    VdDetailAPIAveRespTime_all += VdDetailAPIAveRespTime
                    VdUrlAPIAveRespTime_all += VdUrlAPIAveRespTime_all
                    
                    jcjishu = jcjishu + 1
                
                #print eval("%s%s" % ('UV','_all'))
                
                #生成线性图
                xianx = "["
                
                for xy in xrange(len(days_l)):
                    yy = days_l[xy]['days'][0:4]
                    mm = days_l[xy]['days'][4:6]
                    dd = days_l[xy]['days'][6:]
                    xianx += "'%s/%s/%s'," % (yy,mm,dd)
                xianx = xianx.rstrip(",")
                xianx += "]" 
                
                xiany = "["
                for items_value in _items:
                    shuzu = eval("%s%s" % (items_value,'_list'))
                    shuzu_str = ",".join(shuzu)
                    qiangzu = []
                    qiangzu.append(items_value)
                    mingzi = cnsort.valueFullNameArr(qiangzu)
                    #xiany += "{name: '%s',data: [%s]}," % (mingzi[0],shuzu_str)
                    xiany += "[%s]," % (shuzu_str)            
                xiany = xiany.rstrip(",")
                xiany += "]"                
                #print xianx
                #生成表格
                table = ""
                for xy in xrange(len(days_l)):
                    if xy % 2 ==0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                    table += "<tr %s><td>%s(%s)</td>" % (bg,cnsort.fordate(days_l[xy]['days'],3),common.getxingqi(days_l[xy]['days']))
                    
                    for items_value in _items:
                        table += cnsort.genTableResultInc3(days_l[xy-1].get(items_value),days_l[xy].get(items_value),items_value,xy,days_l)
                    table +="</tr>"
                #生成合计
                table += u"</tbody><tfoot><tr><th class='new_silver_first_n footer'>合计</th>"
                for items_value in _items:
                        if cnsort.checkValueMode(items_value):
                            shu = eval("%s%s" % (items_value,'_all'))
                            
                            if items_value == "CompVV":
                                try:
                                    shu = shu / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    table += "<th style=\"text-align:right;\" class=\"footer\">%s0%%</th>" % (shu*100)
                                else:
                                    table += "<th style=\"text-align:right;\" class=\"footer\">%s%%</th>" % (shu*100)
                            elif items_value == "BefDurTime":
                                
                                table += "<th style=\"padding:0px;\" class=\"footer\">"
                                
                                shu = eval("%s%s" % (items_value,'_all'))
                                table += "<div class='verdivri'>%s</div>" % shu
                                    
                                try:
                                    shu = b3 / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    table += "<div class='verdivri'>%s0%%</div>" % (shu*100)
                                else:
                                    table += "<div class='verdivri'>%s%%</div>" % (shu*100)
                                    
                                try:
                                    shu = b5 / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    table += "<div class='verdivri'>%s0%%</div>" % (shu*100)
                                else:
                                    table += "<div class='verdivri'>%s%%</div>" % (shu*100)
                                    
                                try:
                                    shu = b8 / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    table += "<div class='verdivri'>%s0%%</div>" % (shu*100)
                                else:
                                    table += "<div class='verdivri'>%s%%</div>" % (shu*100)
                                    
                                try:
                                    shu = b300 / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    table += "<div class='verdivri'>%s0%%</div>" % (shu*100)
                                else:
                                    table += "<div class='verdivri'>%s%%</div>" % (shu*100)
                                    
                                try:
                                    shu = b301 / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    table += "<div class='verdivri'>%s0%%</div>" % (shu*100)
                                else:
                                    table += "<div class='verdivri'>%s%%</div>" % (shu*100)
                                
                                
                                
                                table += "<th>"
                                
                                
                            else:
                                try:
                                    shu = shu / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,2)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 2:
                                    table += "<th style=\"text-align:right;\" class=\"footer\">%s0</th>" % shu
                                else:
                                    table += "<th style=\"text-align:right;\" class=\"footer\">%s</th>" % shu
                        else:
                            shu = eval("%s%s" % (items_value,'_all'))
                            table += "<th style=\"text-align:right;\" class=\"footer\">%s</th>" % cnsort.num2money(shu)
                
                table += "</tr>"
                
                zongzong = {}
                zongzong['day'] = len(days_l)
                zongzong['pv_all'] = pv_all
                zongzong['UV_all'] = UV_all
                zongzong['VV_all'] = VV_all
                zongzong['NU_all'] = NU_all
                zongzong['VVUV_all'] = VVUV_all
                zongzong['Dur_all'] = Dur_all
                zongzong['DurVV_all'] = DurVV_all
                zongzong['DurUV_all'] = DurUV_all
                zongzong['Comp_all'] = Comp_all
                zongzong['CompVV_all'] = CompVV_all
                    
                zongzong['BefDurTime_all'] = BefDurTime_all
                zongzong['PlayDurTime_all'] = PlayDurTime_all
                zongzong['PlayTimeVV_all'] = PlayTimeVV_all
                zongzong['PlayDurVV_all'] = PlayDurVV_all
                zongzong['HDSDDurTime_all'] = HDSDDurTime_all
                zongzong['SDHDDurTime_all'] = SDHDDurTime_all
                zongzong['RelateAPIAveRespTime_all'] = RelateAPIAveRespTime_all
                zongzong['VdDetailAPIAveRespTime_all'] = VdDetailAPIAveRespTime_all
                zongzong['VdUrlAPIAveRespTime_all'] = VdUrlAPIAveRespTime_all
                
                fv = {}
                
                fv['table'] = table
                fv['zongzong'] = zongzong
                fv['xianx'] = xianx
                fv['xiany'] = xiany
                
                fanhui[xunhuan[vxunhuan]['name']] = fv
                
            #生成饼图
            blist = ['UV','VV','NU','Comp','Dur']
            if _osid == "":
                fc = {}
                for blist_value in blist:
                    kvalue = "%s%s" % (blist_value,'_all')
                    _android = fanhui['Android']['zongzong'][kvalue]
                    _ios = fanhui['iOS']['zongzong'][kvalue]
                    _wp7 = fanhui['WP7']['zongzong'][kvalue]
                    dd = "[['Android',%s],['Ios',%s],['WP7',%s]]" % (_android,_ios,_wp7)
                    fc[blist_value] = dd 
            elif _device_type == "":
                fc = {}
                for blist_value in blist:
                    kvalue = "%s%s" % (blist_value,'_all')
                    _phone = fanhui['Phone']['zongzong'][kvalue]
                    _pad = fanhui['Pad']['zongzong'][kvalue]
                    dd = "[['Phone',%s],['Pad',%s]]" % (_phone,_pad)
                    fc[blist_value] = dd 
            elif _pm == "":
                fc = {}
                for blist_value in blist:
                    kvalue = "%s%s" % (blist_value,'_all')
                    _changshang = fanhui['changshang']['zongzong'][kvalue]
                    _qudao = fanhui['qudao']['zongzong'][kvalue]
                    dd = u"[['厂商内置',%s],['渠道推广',%s]]" % (_changshang,_qudao)
                    fc[blist_value] = dd
            else:
                fc = '123'
            fanhui['All']['bingtu'] = fc
                
            c.close()
            db.close()
            _url = hashlib.md5(_url)
            _url.digest()
            try:
                mc.set(_url.hexdigest(),fanhui,1024*1024)
            except:
                pass
        else:
            fanhui = m_value
        self.write(fanhui)
        self.finish()
        
        
class NewMainVideo(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
    
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        _pm = self.get_argument('pm','').strip()
        _items = self.get_argument('items','UV,VV,').strip()

        
        
        
        _items = _items.rstrip(',')
        _items = _items.split(",")
        
        """
        AboutDiv = ""
        for _it in _items:
            if _it in common.AboutVideo:
                AboutDiv += common.AboutVideo[_it]
        """
        
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        m_value = mc.get(_md5.hexdigest()) or {}
        
        #print settings.cache_on
        if settings.cache_on == 0:
            m_value = {}
            #print '123'
        
        
        if not m_value:
            
            try:
                st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                return
            
            if not _pd:
                ed_time = datetime.datetime.now()
                delta = ed_time - st_time 
                _pd =  abs(delta.days)
            
            _pd = int(_pd)
            et_time = st_time + datetime.timedelta(days=_pd)
            st_datestr = st_time.strftime('%Y%m%d')
            et_datestr = et_time.strftime('%Y%m%d')
            
            all_data = []
            results = {}
            os_data = []
            days = []
            for i in xrange(0,_pd):
                now = datetime.datetime.strptime(st_datestr,'%Y%m%d')
                delta = datetime.timedelta(days=i)  
                n_days = now + delta  
                days.append(n_days.strftime('%Y%m%d'))

            if _osid == "":
                xunhuan = [{'name':'All','id':'61,59,52','tid':'-1'},{'name':'Android','id':'61','tid':'61'},{'name':'iOS','id':'52','tid':'52'},{'name':'WP7','id':'59','tid':'59'}]
            elif _device_type == "":
                xunhuan = [{'name':'All','id':'1,2','tid':'-1'},{'name':'Phone','id':'1','tid':'1'},{'name':'Pad','id':'2','tid':'2'}]
            elif _pm == "":
                xunhuan = [{'name':'All','id':'1,3,2,8','tid':'-1'},{'name':'qudao','id':'2,8','tid':'2,8'},{'name':'changshang','id':'1','tid':'1'}]
            else:
                xunhuan = [{'name':'All'}]
            
            db = connectMySQL.connMySQL_stat()
            print db
            c=db.cursor()
            fanhui = {}
            _table = "stat_day_total_collect"
            for vxunhuan in xrange(len(xunhuan)):
                
                
                if _pm != "":
                    _pmsql = " and partner_mode in (%s) " % _pm
                else:
                    _pmsql = " "
                tihuanriqi = "tihuanriqi"
                if _osid == "":
                    if _osid == "" and _device_type == "" and _pm == "":
                        sql = " SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server,sum(play_hd_times),sum(play_hd_duration),sum(play_sd_times),sum(play_sd_duration),sum(play_hd2_times),sum(play_hd2_duration)   FROM `%s` WHERE date >= %s and date < %s  and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (1,2) and partner_mode in (1,2,3,8) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' %s group by date " % (_table,st_datestr,et_datestr,xunhuan[vxunhuan]['id'],common.clear_date())
                        sql_apiresp = " SELECT apiresp FROM `%s` WHERE date = %s and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (1,2) and partner_mode in (1,2,3,8) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and apiresp != '' " % (_table,tihuanriqi,xunhuan[vxunhuan]['id'])
                        
                        sql_tu = " SELECT sum(total_user),date FROM `stat_day_user` WHERE app_type = 1 and os_id  = %s  and  device_type  = -1 group by date " % (xunhuan[vxunhuan]['tid'])
                        
                        sql_bdur = "  select sum(num),date,time_type from stat_duration_result where duration_type = 1 and date >= %s and date < %s  and  pid_stat=1 and os_id in (%s) and device_type in (1,2) and business_type = 2 and partner_mode in (1,2,3,8) and ver = 'ALL' and prov = 'ALL' and city = 'ALL'   group by date,time_type " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'])
                        
                        
                        sql_pdur = "  select sum(num),date,time_type from stat_duration_result where duration_type = 2 and date >= %s and date < %s  and  pid_stat=1 and os_id in (%s) and device_type in (1,2) and business_type = 2 and partner_mode in (1,2,3,8) and ver = 'ALL' and prov = 'ALL' and city = 'ALL'   group by date,time_type " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'])
                        
                       
                        
                    elif _osid == "" and _device_type != "":
                        sql = "SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server,sum(play_hd_times),sum(play_hd_duration),sum(play_sd_times),sum(play_sd_duration),sum(play_hd2_times),sum(play_hd2_duration)  FROM `%s` WHERE date >= %s and date < %s and  business_type=2 and pid_stat=1 and os_id in (%s) and  ver = 'ALL' and prov = 'ALL' and city = 'ALL'  and device_type in (%s) %s %s  group by date " % (_table,st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type,_pmsql,common.clear_date())
                        
                        
                        sql_tu = " SELECT sum(total_user),date FROM `stat_day_user` WHERE app_type = 1 and os_id  = %s  and  device_type  = %s group by date " % (xunhuan[vxunhuan]['tid'],_device_type)
                        
                        
                        sql_apiresp = "SELECT apiresp FROM `%s` WHERE date = %s and  business_type=2 and pid_stat=1 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and apiresp != ''  and device_type in (%s) %s  " % (_table,tihuanriqi,xunhuan[vxunhuan]['id'],_device_type,_pmsql)
                        
                        sql_bdur = "  select sum(num),date,time_type from stat_duration_result where duration_type = 1 and date >= %s and date < %s  and  pid_stat=1 and business_type = 2 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and device_type in (%s) %s  group by date,time_type " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type,_pmsql)
                        
                        sql_pdur = "  select sum(num),date,time_type from stat_duration_result where duration_type = 2 and date >= %s and date < %s  and  pid_stat=1 and business_type = 2 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and device_type in (%s) %s  group by date,time_type " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type,_pmsql)
                        
                    elif _osid == "" and _device_type == "":
                        sql = "SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server,sum(play_hd_times),sum(play_hd_duration),sum(play_sd_times),sum(play_sd_duration),sum(play_hd2_times),sum(play_hd2_duration)  FROM `%s` WHERE date >= %s and date < %s and  business_type=2 and pid_stat=1 and os_id in (%s) and ver = 'ALL'   and prov = 'ALL' and city = 'ALL'   and device_type in (1,2) %s %s group by date " % (_table,st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_pmsql,common.clear_date())
                        sql_apiresp = "SELECT apiresp FROM `%s` WHERE date = %s and  business_type=2 and pid_stat=1 and os_id in (%s) and ver = 'ALL'  and prov = 'ALL' and city = 'ALL' and apiresp != '' and device_type in (1,2) %s  " % (_table,tihuanriqi,xunhuan[vxunhuan]['id'],_pmsql)
                        
                        
                        sql_tu = " SELECT sum(total_user),date FROM `stat_day_user` WHERE app_type = 1 and os_id  = %s  and  device_type  = -1 group by date " % (xunhuan[vxunhuan]['tid'])
                        
                        
                        sql_bdur = "  select sum(num),date,time_type from stat_duration_result where duration_type = 1 and date >= %s and date < %s  and  pid_stat=1 and business_type = 2 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and device_type in (1,2) %s  group by date,time_type " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_pmsql)
                        
                        sql_pdur = "  select sum(num),date,time_type from stat_duration_result where duration_type = 2 and date >= %s and date < %s  and  pid_stat=1 and business_type = 2 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and device_type in (1,2) %s  group by date,time_type " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_pmsql)
                        
                elif _device_type == "":
                        sql = " SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server,sum(play_hd_times),sum(play_hd_duration),sum(play_sd_times),sum(play_sd_duration),sum(play_hd2_times),sum(play_hd2_duration)  FROM `%s` WHERE date >= %s and date < %s and  business_type=2 and pid_stat=1  and os_id in (%s) and ver = 'ALL'   and prov = 'ALL' and city = 'ALL'    and device_type in (%s) %s %s  group by date" % (_table,st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'],_pmsql,common.clear_date())
                        sql_apiresp = " SELECT apiresp FROM `%s` WHERE date = %s and  business_type=2 and pid_stat=1 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and apiresp != '' and  device_type in (%s) %s " % (_table,tihuanriqi,_osid,xunhuan[vxunhuan]['id'],_pmsql)
                        
                        
                        sql_tu = " SELECT sum(total_user),date FROM `stat_day_user` WHERE app_type = 1 and os_id  = %s  and  device_type  = %s group by date " % (_osid,xunhuan[vxunhuan]['tid'])
                        
                        
                        sql_bdur = "  select sum(num),date,time_type from stat_duration_result where duration_type = 1 and date >= %s and date < %s  and  pid_stat=1 and business_type = 2 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and device_type in (%s) %s  group by date,time_type " % (st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'],_pmsql)
                        
                        sql_bdur = "  select sum(num),date,time_type from stat_duration_result where duration_type = 2 and date >= %s and date < %s  and  pid_stat=1 and business_type = 2 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and device_type in (%s) %s  group by date,time_type " % (st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'],_pmsql)
                        
                elif _pm == "":
                        sql = " SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server,sum(play_hd_times),sum(play_hd_duration),sum(play_sd_times),sum(play_sd_duration),sum(play_hd2_times),sum(play_hd2_duration)  FROM `%s` WHERE date >= %s and date < %s and  business_type=2 and pid_stat=1 and os_id in (%s) and ver = 'ALL'   and prov = 'ALL' and city = 'ALL'   and  device_type in (%s) and partner_mode in (%s)  %s   group by date " % (_table,st_datestr,et_datestr,_osid,_device_type,xunhuan[vxunhuan]['id'],common.clear_date())
                        sql_apiresp = " SELECT apiresp FROM `%s` WHERE date = %s and  business_type=2 and pid_stat=1 and os_id in (%s) and ver = 'ALL'   and prov = 'ALL' and city = 'ALL'  and  device_type in (%s) and partner_mode in (%s) and apiresp != '' " % (_table,tihuanriqi,_osid,_device_type,xunhuan[vxunhuan]['id'])
                        
                        
                        sql_tu = " SELECT sum(total_user),date FROM `stat_day_user` WHERE app_type = 1 and os_id  = %s  and  device_type  = %s group by date " % (_osid,_device_type)
                        
                        sql_bdur = "  select sum(num),date,time_type from stat_duration_result where duration_type = 1 and date >= %s and date < %s  and  pid_stat=1 and business_type = 2 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and  device_type in (%s) and partner_mode in (%s)  group by date,time_type " % (st_datestr,et_datestr,_osid,_device_type,xunhuan[vxunhuan]['id'])
                        
                        sql_bdur = "  select sum(num),date,time_type from stat_duration_result where duration_type = 2 and date >= %s and date < %s  and  pid_stat=1 and business_type = 2 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and  device_type in (%s) and partner_mode in (%s)  group by date,time_type " % (st_datestr,et_datestr,_osid,_device_type,xunhuan[vxunhuan]['id'])
                        
                else:
                        sql = "SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server,sum(play_hd_times),sum(play_hd_duration),sum(play_sd_times),sum(play_sd_duration),sum(play_hd2_times),sum(play_hd2_duration)  FROM `%s` WHERE date >= %s and date < %s and  business_type=2 and pid_stat=1 and os_id in (%s) and ver = 'ALL'   and prov = 'ALL' and city = 'ALL'    and   device_type in (%s) and partner_mode in (%s) %s  group by date " % (_table,st_datestr,et_datestr,_osid,_device_type,_pm,common.clear_date())
                        sql_apiresp = "SELECT apiresp FROM `%s` WHERE date = %s and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (%s) and ver = 'ALL'  and prov = 'ALL' and city = 'ALL' and   partner_mode in (%s) and apiresp != '' " % (_table,tihuanriqi,_osid,_device_type,_pm)
                        
                        
                        sql_tu = " SELECT sum(total_user),date FROM `stat_day_user` WHERE app_type = 1 and os_id  = %s  and  device_type  = %s group by date " % (_osid,_device_type)
                        
                        sql_bdur = "  select sum(num),date,time_type from stat_duration_result where duration_type = 1 and date >= %s and date < %s  and  pid_stat=1 and business_type = 2 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and   device_type in (%s) and partner_mode in (%s)  group by date,time_type " % (st_datestr,et_datestr,_osid,_device_type,_pm)
                        
                        sql_pdur = "  select sum(num),date,time_type from stat_duration_result where duration_type = 2 and date >= %s and date < %s  and  pid_stat=1 and business_type = 2 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and   device_type in (%s) and partner_mode in (%s)  group by date,time_type " % (st_datestr,et_datestr,_osid,_device_type,_pm)
                        
                        
                #print sql_bdur
                print sql
                c.execute(sql)  
                result_all = c.fetchall()
                #print sql_bdur
                
                if "BefDurTime123" in _items:
                    c.execute(sql_bdur)
                    result_bdur = c.fetchall()
                else:
                    result_bdur = []
                    
                if "PlayDurTime123" in _items:
                    c.execute(sql_pdur)
                    result_pdur = c.fetchall()
                else:
                    result_pdur = []
                    
                if "TU" in _items:
                    c.execute(sql_tu)
                    result_tu = c.fetchall()
                else:
                    result_tu = []
                
                UV_list = []
                TU_list = []
                pv_list = []
                NU_list = []
                VV_list = []
                VVUV_list = []
                Dur_list = []
                DurVV_list = []
                DurUV_list = []
                Comp_list = []
                CompVV_list = []
                BefDurTime_list = []
                PlayDurTime_list = []
                PlayTimeVV_list = []
                PlayDurVV_list = []
                HDSDDurTime_list = []
                SDHDDurTime_list = []
                HD2DurTime_list = []
                RelateAPIAveRespTime_list = []
                VdDetailAPIAveRespTime_list = []
                VdUrlAPIAveRespTime_list = []
                
                
                TU_all = 0
                b3_all = 0
                b5_all = 0
                b8_all = 0
                b300_all = 0
                b301_all = 0
                
                p3_all = 0
                p5_all = 0
                p8_all = 0
                p300_all = 0
                p301_all = 0
                
                pv_all = 0
                UV_all = 0
                NU_all = 0
                VV_all = 0
                VVUV_all = 0
                Dur_all = 0
                DurVV_all = 0
                DurUV_all = 0
                Comp_all = 0
                CompVV_all = 0
                    
                BefDurTime_all = 0
                PlayDurTime_all = 0
                PlayTimeVV_all = 0
                PlayDurVV_all = 0
                HDSDDurTime_all = 0
                SDHDDurTime_all = 0
                HD2DurTime_all = 0
                RelateAPIAveRespTime_all = 0
                VdDetailAPIAveRespTime_all = 0
                VdUrlAPIAveRespTime_all = 0
                
                days_l = []
                jiriqi = []
                for result in result_all:
                    jiriqi.append(str(result[0]))
                
                
                jcjishu = 0
                for result in result_all:
                    
                    _riqi = str(result[0])
                    
                    b3 = 0
                    b5 = 0
                    b8 = 0
                    b300 = 0
                    b301 = 0
                    
                    p3 = 0
                    p5 = 0
                    p8 = 0
                    p300 = 0
                    p301 = 0
                    TU = 0
                    
                    for tuv in result_tu:
                        if _riqi == str(tuv[1]):
                            TU = int(tuv[0])
                            
                    pv = int(result[3])
                    UV = int(result[4])
                    VV = int(result[5])
                    try:
                        VVUV = VV / UV
                    except:
                        VVUV = 0
                    Dur = int(result[10])
                    Dur = Dur / 60
                    try:
                        DurVV = Dur / VV
                    except:
                        DurVV = 0
                    try:
                        DurUV = Dur / UV
                    except:
                        DurUV = 0
                    DurVV = round(DurVV,2)
                    DurUV = round(DurUV,2)    
                    VVUV = round(VVUV,2)
                    Comp = int(result[11])
                        
                    NU = int(result[6])
                    pm = int(result[7])
                        
                    try:
                        CompVV = Comp / VV
                    except:
                        CompVV = 0
                    CompVV = round(CompVV,4)
                        
                        
                    before_duration = int(result[8])
                    before_times = int(result[9])
                    
                    #print before_duration,before_times
                        
                    if (before_duration == 0 or before_times == 0):
                        BefDurTime = 0
                    else:
                        BefDurTime = before_duration/before_times/1000
                        
                    BefDurTime = round(BefDurTime,2)
                        
                    play_load_duration = int(result[12])
                    play_load_times = int(result[13])
                        
                    if (play_load_duration == 0 or play_load_times == 0):
                        PlayDurTime = 0
                    else:
                        PlayDurTime = play_load_duration/play_load_times/1000
                        
                    PlayDurTime = round(PlayDurTime,2)
                        
                    if (play_load_times == 0 or VV == 0):
                        PlayTimeVV = 0
                    else:
                        PlayTimeVV = play_load_times/VV
                        
                    PlayTimeVV = round(PlayTimeVV,2)
                        
                    if (play_load_duration == 0 or VV == 0):
                        PlayDurVV = 0
                    else:
                        PlayDurVV = play_load_duration/VV/1000
                        
                    
                    play_hd_times = int(result[20])

                    play_hd_duration = int(result[21])

                    play_sd_times = int(result[22])

                    play_sd_duration = int(result[23])

                    play_hd2_times = int(result[24])

                    play_hd2_duration = int(result[25])

                        
                    PlayDurVV = round(PlayDurVV,2)
                    play_hdsd_times = int(result[14])
                    play_hdsd_duration = int(result[15])
                    
                    play_hdsd_durationhe = play_sd_duration + play_hdsd_duration
                    play_hdsd_timeshe = play_sd_times + play_hdsd_times
                    
                        
                    if (play_hdsd_durationhe == 0 or play_hdsd_timeshe == 0):
                        HDSDDurTime = 0
                    else:
                        HDSDDurTime = play_hdsd_durationhe/play_hdsd_timeshe/1000
                        
                    HDSDDurTime = round(HDSDDurTime,2)
                        
                    play_sdhd_times = int(result[16])
                    play_sdhd_duration = int(result[17])
                    
                    
                    play_sdhd_durationhe = play_sd_duration + play_sdhd_duration
                    play_sdhd_timeshe = play_sd_times + play_sdhd_times
                        
                    if (play_sdhd_durationhe == 0 or play_sdhd_timeshe == 0):
                        SDHDDurTime = 0
                    else:
                        SDHDDurTime = play_sdhd_durationhe/play_sdhd_timeshe/1000
                    
                    SDHDDurTime = round(SDHDDurTime,2)
                        
                        
                    if (play_hd2_duration == 0 or play_hd2_times == 0):
                        HD2DurTime = 0
                    else:
                        HD2DurTime = play_hd2_duration/play_hd2_times/1000
                        
                    HD2DurTime = round(HD2DurTime,2)
                    
                    
                    
                    if jcjishu == 0:
                        sql_apiresp = sql_apiresp.replace("tihuanriqi",str(result[0]))
                    else:
                        sql_apiresp = sql_apiresp.replace(jiriqi[jcjishu-1],str(result[0]))
                    
                    
                    
                    cha = 0
                    xuyao_ziduan = ['RelateAPIAveRespTime','VdDetailAPIAveRespTime','VdUrlAPIAveRespTime']
    
                    cha = len(set(_items) & set(xuyao_ziduan))
                    
                    
                    if cha != 0:
                        play_resptime,play_times,draw_resptime,draw_times,getVideoDetail_resptime,getVideoDetail_times = clientcache.getJsondata_new(sql_apiresp)
                    else:
                        play_resptime = 0
                        play_times = 0
                        draw_resptime = 0
                        draw_times = 0
                        getVideoDetail_resptime = 0
                        getVideoDetail_times = 0
                        
                    if (draw_resptime == 0 or draw_times == 0):
                        RelateAPIAveRespTime = 0
                    else:
                        RelateAPIAveRespTime = draw_resptime/draw_times/1000
                        
                    RelateAPIAveRespTime = round(RelateAPIAveRespTime,2)
                        
                    if (getVideoDetail_resptime == 0 or getVideoDetail_times == 0):
                        VdDetailAPIAveRespTime = 0
                    else:
                        VdDetailAPIAveRespTime = getVideoDetail_resptime/getVideoDetail_times/1000
                        
                    VdDetailAPIAveRespTime = round(VdDetailAPIAveRespTime,2)
                    if (play_resptime == 0 or play_times == 0):
                        VdUrlAPIAveRespTime = 0
                    else:
                        VdUrlAPIAveRespTime = play_resptime/play_times/1000
                        
                    VdUrlAPIAveRespTime = round(VdUrlAPIAveRespTime,2)                    
                    
                        
                    
                    
                    TU_list.append(str(TU))
                    UV_list.append(str(UV))
                    pv_list.append(str(pv))
                    NU_list.append(str(NU))
                    VV_list.append(str(VV))
                    VVUV_list.append(str(VVUV))
                    Dur_list.append(str(Dur))
                    DurVV_list.append(str(DurVV))
                    DurUV_list.append(str(DurUV))
                    Comp_list.append(str(Comp))
                    CompVV_list.append(str(CompVV))
                    BefDurTime_list.append(str(BefDurTime))
                    PlayDurTime_list.append(str(PlayDurTime))
                    PlayTimeVV_list.append(str(PlayTimeVV))
                    PlayDurVV_list.append(str(PlayDurVV))
                    HDSDDurTime_list.append(str(HDSDDurTime))
                    HD2DurTime_list.append(str(HD2DurTime))
                    SDHDDurTime_list.append(str(SDHDDurTime))
                    RelateAPIAveRespTime_list.append(str(RelateAPIAveRespTime))
                    VdDetailAPIAveRespTime_list.append(str(VdDetailAPIAveRespTime))
                    VdUrlAPIAveRespTime_list.append(str(VdUrlAPIAveRespTime))
                    
                    bdurtime = {}
                    
                    bdurtime['pingjun'] = BefDurTime
                    
                    pdurtime = {}
                    
                    pdurtime['pingjun'] = PlayDurTime
                    
                    
                    
                    try:
                        zhanbib = int(b3) / int(result[9])
                    except:
                        zhanbib = 0
                    b3 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(b5) / int(result[9])
                    except:
                        zhanbib = 0
                    b5 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(b8) / int(result[9])
                    except:
                        zhanbib = 0
                    b8 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(b300) / int(result[9])
                    except:
                        zhanbib = 0
                    b300 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(b301) / int(result[9])
                    except:
                        zhanbib = 0
                    b301 = round(zhanbib,2)
                    
                    
                    
                    try:
                        zhanbib = int(p3) / int(result[13])
                    except:
                        zhanbib = 0
                    p3 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(p5) / int(result[13])
                    except:
                        zhanbib = 0
                    p5 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(p8) / int(result[13])
                    except:
                        zhanbib = 0
                    p8 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(p300) / int(result[13])
                    except:
                        zhanbib = 0
                    p300 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(p301) / int(result[13])
                    except:
                        zhanbib = 0
                    p301 = round(zhanbib,2)
                    
                    
                    
                    bdurtime['b3'] = b3
                    bdurtime['b5'] = b5
                    bdurtime['b8'] = b8
                    bdurtime['b300'] = b300
                    bdurtime['b301'] = b301
                    bdurtime['zong'] = int(result[9])
                    
                    
                    
                    pdurtime['p3'] = p3
                    pdurtime['p5'] = p5
                    pdurtime['p8'] = p8
                    pdurtime['p300'] = p300
                    pdurtime['p301'] = p301
                    pdurtime['zong'] = int(result[13])
                    

                    
                    days_l.append({'days':_riqi,'pv':pv,'UV':UV,'VV':VV,'NU':NU,'VVUV':VVUV,'Dur':Dur,'DurVV':DurVV,'DurUV':DurUV,'Comp':Comp,'CompVV':CompVV,'BefDurTime':BefDurTime,'PlayDurTime':PlayDurTime,'PlayTimeVV':PlayTimeVV,'HDSDDurTime':HDSDDurTime,'SDHDDurTime':SDHDDurTime,'HD2DurTime':HD2DurTime,'RelateAPIAveRespTime':RelateAPIAveRespTime,'VdDetailAPIAveRespTime':VdDetailAPIAveRespTime,'VdUrlAPIAveRespTime':VdUrlAPIAveRespTime,'PlayDurVV':PlayDurVV,'bdurtime':bdurtime,'pdurtime':pdurtime,'TU':TU})
                    
                    
                    
                    b3_all += b3
                    b5_all += b5
                    b8_all += b8
                    b300_all += b300
                    b301_all += b301
                    
                    p3_all += p3
                    p5_all += p5
                    p8_all += p8
                    p300_all += p300
                    p301_all += p301
                    
                    
                    pv_all += pv
                    TU_all += TU
                    UV_all += UV
                    NU_all += NU
                    VV_all += VV
                    VVUV_all += VVUV
                    Dur_all += Dur
                    DurVV_all += DurVV
                    DurUV_all += DurUV
                    Comp_all += Comp
                    CompVV_all += CompVV
                    
                    BefDurTime_all += BefDurTime
                    PlayDurTime_all += PlayDurTime
                    PlayTimeVV_all += PlayTimeVV
                    PlayDurVV_all += PlayDurVV
                    HDSDDurTime_all += HDSDDurTime
                    SDHDDurTime_all += SDHDDurTime
                    HD2DurTime_all += HD2DurTime
                    RelateAPIAveRespTime_all += RelateAPIAveRespTime
                    VdDetailAPIAveRespTime_all += VdDetailAPIAveRespTime
                    VdUrlAPIAveRespTime_all += VdUrlAPIAveRespTime_all
                    
                    jcjishu = jcjishu + 1
                
                #print eval("%s%s" % ('UV','_all'))
                
                #生成线性图
                xianx = "["
                
                for xy in xrange(len(days_l)):
                    yy = days_l[xy]['days'][0:4]
                    mm = days_l[xy]['days'][4:6]
                    dd = days_l[xy]['days'][6:]
                    xianx += "'%s/%s/%s'," % (yy,mm,dd)
                xianx = xianx.rstrip(",")
                xianx += "]" 
                
                xiany = "["
                for items_value in _items:
                    shuzu = eval("%s%s" % (items_value,'_list'))
                    shuzu_str = ",".join(shuzu)
                    qiangzu = []
                    qiangzu.append(items_value)
                    mingzi = cnsort.valueFullNameArr(qiangzu)
                    #xiany += "{name: '%s',data: [%s]}," % (mingzi[0],shuzu_str)
                    xiany += "[%s]," % (shuzu_str)            
                xiany = xiany.rstrip(",")
                xiany += "]"                
                #print xianx
                #生成表格
                table = ""
                for xy in xrange(len(days_l)):
                    if xy % 2 ==0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                    table += "<tr %s><td>%s(%s)</td>" % (bg,cnsort.fordate(days_l[xy]['days'],3),common.getxingqi(days_l[xy]['days']))
                    
                    for items_value in _items:
                        table += cnsort.genTableResultInc3(days_l[xy-1].get(items_value),days_l[xy].get(items_value),items_value,xy,days_l)
                    table +="</tr>"
                #生成合计
                table += u"</tbody><tfoot><tr><th class='new_silver_first_n footer'>合计</th>"
                for items_value in _items:
                        if cnsort.checkValueMode(items_value):
                            shu = eval("%s%s" % (items_value,'_all'))
                            
                            if items_value == "CompVV":
                                try:
                                    shu = shu / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    table += "<th style=\"text-align:right;\" class=\"footer\">%s0%%</th>" % (shu*100)
                                else:
                                    table += "<th style=\"text-align:right;\" class=\"footer\">%s%%</th>" % (shu*100)
                            elif items_value == "BefDurTime123":
                                
                                table += "<th style=\"padding:0px;\" class=\"footer\">"
                                
                                shu = eval("%s%s" % (items_value,'_all'))
                                table += "<div class='verdivri'>%s</div>" % shu
                                    
                                try:
                                    shu = b3_all / len(days_l)
                                except:
                                    shu = 0
                                print shu,len(days_l)
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    table += "<div class='verdivri'>%s0%%</div>" % (shu*100)
                                else:
                                    table += "<div class='verdivri'>%s%%</div>" % (shu*100)
                                    
                                try:
                                    shu = b5_all / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    table += "<div class='verdivri'>%s0%%</div>" % (shu*100)
                                else:
                                    table += "<div class='verdivri'>%s%%</div>" % (shu*100)
                                    
                                try:
                                    shu = b8_all / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    table += "<div class='verdivri'>%s0%%</div>" % (shu*100)
                                else:
                                    table += "<div class='verdivri'>%s%%</div>" % (shu*100)
                                    
                                try:
                                    shu = b300_all / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    table += "<div class='verdivri'>%s0%%</div>" % (shu*100)
                                else:
                                    table += "<div class='verdivri'>%s%%</div>" % (shu*100)
                                    
                                try:
                                    shu = b301_all / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    table += "<div class='verdivri'>%s0%%</div>" % (shu*100)
                                else:
                                    table += "<div class='verdivri'>%s%%</div>" % (shu*100)
                                
                        
                                table += "</th>"
                            
                            elif items_value == "PlayDurTime123":
                                
                                table += "<th style=\"padding:0px;\" class=\"footer\">"
                                
                                shu = eval("%s%s" % (items_value,'_all'))
                                table += "<div class='verdivri'>%s</div>" % shu
                                    
                                try:
                                    shu = p3_all / len(days_l)
                                except:
                                    shu = 0
                                #print shu,len(days_l)
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    table += "<div class='verdivri'>%s0%%</div>" % (shu*100)
                                else:
                                    table += "<div class='verdivri'>%s%%</div>" % (shu*100)
                                    
                                try:
                                    shu = p5_all / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    table += "<div class='verdivri'>%s0%%</div>" % (shu*100)
                                else:
                                    table += "<div class='verdivri'>%s%%</div>" % (shu*100)
                                    
                                try:
                                    shu = p8_all / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    table += "<div class='verdivri'>%s0%%</div>" % (shu*100)
                                else:
                                    table += "<div class='verdivri'>%s%%</div>" % (shu*100)
                                    
                                try:
                                    shu = p300_all / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    table += "<div class='verdivri'>%s0%%</div>" % (shu*100)
                                else:
                                    table += "<div class='verdivri'>%s%%</div>" % (shu*100)
                                    
                                try:
                                    shu = p301_all / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    table += "<div class='verdivri'>%s0%%</div>" % (shu*100)
                                else:
                                    table += "<div class='verdivri'>%s%%</div>" % (shu*100)
                                
                        
                                table += "</th>"    
                            
                            else:
                                try:
                                    shu = shu / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,2)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 2:
                                    table += "<th style=\"text-align:right;\" class=\"footer\">%s0</th>" % shu
                                else:
                                    table += "<th style=\"text-align:right;\" class=\"footer\">%s</th>" % shu
                        else:
                            shu = eval("%s%s" % (items_value,'_all'))
                            table += "<th style=\"text-align:right;\" class=\"footer\">%s</th>" % cnsort.num2money(shu)
                
                table += "</tr>"
                
                zongzong = {}
                zongzong['day'] = len(days_l)
                zongzong['pv_all'] = pv_all
                zongzong['UV_all'] = UV_all
                zongzong['TU_all'] = TU_all
                zongzong['VV_all'] = VV_all
                zongzong['NU_all'] = NU_all
                zongzong['VVUV_all'] = VVUV_all
                zongzong['Dur_all'] = Dur_all
                zongzong['DurVV_all'] = DurVV_all
                zongzong['DurUV_all'] = DurUV_all
                zongzong['Comp_all'] = Comp_all
                zongzong['CompVV_all'] = CompVV_all
                    
                zongzong['BefDurTime_all'] = BefDurTime_all
                zongzong['PlayDurTime_all'] = PlayDurTime_all
                zongzong['PlayTimeVV_all'] = PlayTimeVV_all
                zongzong['PlayDurVV_all'] = PlayDurVV_all
                zongzong['HDSDDurTime_all'] = HDSDDurTime_all
                zongzong['SDHDDurTime_all'] = SDHDDurTime_all
                zongzong['RelateAPIAveRespTime_all'] = RelateAPIAveRespTime_all
                zongzong['VdDetailAPIAveRespTime_all'] = VdDetailAPIAveRespTime_all
                zongzong['VdUrlAPIAveRespTime_all'] = VdUrlAPIAveRespTime_all
                
                fv = {}
                
                fv['table'] = table
                fv['zongzong'] = zongzong
                fv['xianx'] = xianx
                fv['xiany'] = xiany
                
                fanhui[xunhuan[vxunhuan]['name']] = fv
                
            #生成饼图
            blist = ['UV','VV','NU','Comp','Dur']
            if _osid == "":
                fc = {}
                for blist_value in blist:
                    kvalue = "%s%s" % (blist_value,'_all')
                    _android = fanhui['Android']['zongzong'][kvalue]
                    _ios = fanhui['iOS']['zongzong'][kvalue]
                    _wp7 = fanhui['WP7']['zongzong'][kvalue]
                    dd = "[['Android',%s],['Ios',%s],['WP7',%s]]" % (_android,_ios,_wp7)
                    fc[blist_value] = dd 
            elif _device_type == "":
                fc = {}
                for blist_value in blist:
                    kvalue = "%s%s" % (blist_value,'_all')
                    _phone = fanhui['Phone']['zongzong'][kvalue]
                    _pad = fanhui['Pad']['zongzong'][kvalue]
                    dd = "[['Phone',%s],['Pad',%s]]" % (_phone,_pad)
                    fc[blist_value] = dd 
            elif _pm == "":
                fc = {}
                for blist_value in blist:
                    kvalue = "%s%s" % (blist_value,'_all')
                    _changshang = fanhui['changshang']['zongzong'][kvalue]
                    _qudao = fanhui['qudao']['zongzong'][kvalue]
                    dd = u"[['厂商内置',%s],['渠道推广',%s]]" % (_changshang,_qudao)
                    fc[blist_value] = dd
            else:
                fc = '123'
            fanhui['All']['bingtu'] = fc
                
            c.close()
            db.close()
            _url = hashlib.md5(_url)
            _url.digest()
            try:
                mc.set(_url.hexdigest(),fanhui,1024*1024)
            except:
                pass
        else:
            fanhui = m_value
        self.write(fanhui)
        self.finish()
        


class BeforeDurationMain(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
    
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        _pm = self.get_argument('pm','').strip()
        _items = self.get_argument('items','UV,VV,').strip()
        _items = _items.rstrip(',')
        _items = _items.split(",")
        
        """
        AboutDiv = ""
        for _it in _items:
            if _it in common.AboutVideo:
                AboutDiv += common.AboutVideo[_it]
        """
        
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        m_value = mc.get(_md5.hexdigest()) or {}
        
        #print settings.cache_on
        if settings.cache_on == 0:
            m_value = {}
            #print '123'
        
        m_value = {}
        
        if not m_value:
            
            try:
                st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                return
            
            if not _pd:
                ed_time = datetime.datetime.now()
                delta = ed_time - st_time 
                _pd =  abs(delta.days)
            
            _pd = int(_pd)
            et_time = st_time + datetime.timedelta(days=_pd)
            st_datestr = st_time.strftime('%Y%m%d')
            et_datestr = et_time.strftime('%Y%m%d')
            
            all_data = []
            results = {}
            os_data = []
            days = []
            for i in xrange(0,_pd):
                now = datetime.datetime.strptime(st_datestr,'%Y%m%d')
                delta = datetime.timedelta(days=i)  
                n_days = now + delta  
                days.append(n_days.strftime('%Y%m%d'))
            '''
            if _osid == "":
                xunhuan = [{'name':'All','id':'61,59,52'},{'name':'Android','id':'61'},{'name':'iOS','id':'52'},{'name':'WP7','id':'59'}]
            elif _device_type == "":
                xunhuan = [{'name':'All','id':'1,2'},{'name':'Phone','id':'1'},{'name':'Pad','id':'2'}]
            elif _pm == "":
                xunhuan = [{'name':'All','id':'1,3,2,8'},{'name':'qudao','id':'2,8'},{'name':'changshang','id':'1'}]
            else:
            '''
            
            xunhuan = [{'name':'All'}]
            
            db = connectMySQL.connMySQL_stat()
            c=db.cursor()
            fanhui = {}
            _table = "stat_day_total_collect"
            for vxunhuan in xrange(len(xunhuan)):
                
                
                sql = "SELECT date,sum(before_duration),sum(before_times)  FROM `%s` WHERE date >= %s and date < %s and  business_type=2 and pid_stat=1 and os_id in (%s) and  ver = 'ALL' and prov = 'ALL' and city = 'ALL'  and device_type in (%s) and partner_mode in (%s)  group by date desc " % (_table,st_datestr,et_datestr,_osid,_device_type,_pm)
                        
                sql_bdur = "  select sum(num),date,time_type from stat_duration_result where duration_type = 1 and date >= %s and date < %s  and  pid_stat=1 and business_type = 2 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and device_type in (%s) and partner_mode in (%s)  group by date,time_type " % (st_datestr,et_datestr,_osid,_device_type,_pm)
                
                c.execute(sql)  
                result_all = c.fetchall()
                
                print sql_bdur
                
                c.execute(sql_bdur)
                result_bdur = c.fetchall()
                
                
                
                
                b3_all = 0
                b5_all = 0
                b8_all = 0
                b300_all = 0
                b301_all = 0
                
                p3_all = 0
                p5_all = 0
                p8_all = 0
                p300_all = 0
                p301_all = 0
                
                pv_all = 0
                UV_all = 0
                NU_all = 0
                VV_all = 0
                VVUV_all = 0
                Dur_all = 0
                DurVV_all = 0
                DurUV_all = 0
                Comp_all = 0
                CompVV_all = 0
                    
                BefDurTime_all = 0
                PlayDurTime_all = 0
                PlayTimeVV_all = 0
                PlayDurVV_all = 0
                HDSDDurTime_all = 0
                SDHDDurTime_all = 0
                HD2DurTime_all = 0
                RelateAPIAveRespTime_all = 0
                VdDetailAPIAveRespTime_all = 0
                VdUrlAPIAveRespTime_all = 0
                
                days_l = []
                jiriqi = []
                for result in result_all:
                    jiriqi.append(str(result[0]))
                
                
                jcjishu = 0
                for result in result_all:
                    
                    _riqi = str(result[0])
                    
                    b3 = 0
                    b5 = 0
                    b8 = 0
                    b300 = 0
                    b301 = 0
                    
                    for bdurv in result_bdur:
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 3:
                            b3 = int(bdurv[0])
                        
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 5:
                            b5 = int(bdurv[0])
                            
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 8:
                            b8 = int(bdurv[0])
                            
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 300:
                            b300 = int(bdurv[0])
                        
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 301:
                            b301 = int(bdurv[0])
                    
                    
                    
                        
                        
                    before_duration = int(result[1])
                    before_times = int(result[2])
                    
                    #print before_duration,before_times
                        
                    if (before_duration == 0 or before_times == 0):
                        BefDurTime = 0
                    else:
                        BefDurTime = before_duration/before_times/1000
                        
                    BefDurTime = round(BefDurTime,2)
                        
                    
                    
                    try:
                        zhanbib = int(b3) / int(result[2])
                    except:
                        zhanbib = 0
                    b3 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(b5) / int(result[2])
                    except:
                        zhanbib = 0
                    b5 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(b8) / int(result[2])
                    except:
                        zhanbib = 0
                    b8 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(b300) / int(result[2])
                    except:
                        zhanbib = 0
                    b300 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(b301) / int(result[2])
                    except:
                        zhanbib = 0
                    b301 = round(zhanbib,2)
                    
                    days_l.append({'days':_riqi,'BefDurTime':BefDurTime,'b3':b3,'b5':b5,'b3':b3,'b8':b8,'b300':b300,'b301':b301})
                    
                    b3_all += b3
                    b5_all += b5
                    b8_all += b8
                    b300_all += b300
                    b301_all += b301
                    
                #print xianx
                #生成表格
                table = ""
                for xy in xrange(len(days_l)):
                    if xy % 2 ==0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                    table += "<tr %s><td>%s(%s)</td>" % (bg,cnsort.fordate(days_l[xy]['days'],3),common.getxingqi(days_l[xy]['days']))
                    
                    pingjun = days_l[xy]['BefDurTime']
                    
                    table += "<td style='padding:0px;'>"
        
                    
                    nl = str(days_l[xy]['b3']).split(".")
                    #print nl
                    if len(str(nl[1])) < 4:
                        shu = "%s0%s" % (days_l[xy]['b3'] * 100,"%")
                    else:
                        shu = "%s%s" % (days_l[xy]['b3'] * 100,"%")
                    b3 = shu
                    
                    #print b3
                    
                    
                    
                    nl = str(days_l[xy]['b5']).split(".")
                    #print nl
                    if len(str(nl[1])) < 4:
                        shu = "%s0%s" % (days_l[xy]['b5'] * 100,"%")
                    else:
                        shu = "%s%s" % (days_l[xy]['b5'] * 100,"%")
                    b5 = shu
                    
                    
                    nl = str(days_l[xy]['b8']).split(".")
                    #print nl
                    if len(str(nl[1])) < 4:
                        shu = "%s0%s" % (days_l[xy]['b8'] * 100,"%")
                    else:
                        shu = "%s%s" % (days_l[xy]['b8'] * 100,"%")
                    b8 = shu
                    
                   
                    nl = str(days_l[xy]['b300']).split(".")
                    #print nl
                    if len(str(nl[1])) < 4:
                        shu = "%s0%s" % (days_l[xy]['b300'] * 100,"%")
                    else:
                        shu = "%s%s" % (days_l[xy]['b300'] * 100,"%")
                    b300 = shu
                    
                    nl = str(days_l[xy]['b301']).split(".")
                    #print nl
                    if len(str(nl[1])) < 4:
                        shu = "%s0%s" % (days_l[xy]['b301'] * 100,"%")
                    else:
                        shu = "%s%s" % (days_l[xy]['b301'] * 100,"%")
                    b301 = shu
                    
                    table += "<div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div></td>" % (pingjun,b3,b5,b8,b300,b301)
                    
                    table +="</tr>"
                table += u"</tbody><tfoot>"
                
                fv = {}
                
                fv['table'] = table
                
                fanhui[xunhuan[vxunhuan]['name']] = fv
                
            
            c.close()
            db.close()
            _url = hashlib.md5(_url)
            _url.digest()
            try:
                mc.set(_url.hexdigest(),fanhui,1024*1024)
            except:
                pass
        else:
            fanhui = m_value
        self.write(fanhui)
        self.finish()
        
        
class LocalVv(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
    
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        _bt = self.get_argument('business_type','2').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        _pm = self.get_argument('pm','').strip()
        _items = self.get_argument('items','UV,VV,').strip()
        _items = _items.rstrip(',')
        _items = _items.split(",")
        
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        m_value = mc.get(_md5.hexdigest()) or {}
        
        #print settings.cache_on
        if settings.cache_on == 0:
            m_value = {}
            #print '123'
        
        m_value = {}
        
        if not m_value:
            
            try:
                st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                return
            
            if not _pd:
                ed_time = datetime.datetime.now()
                delta = ed_time - st_time 
                _pd =  abs(delta.days)
            
            _pd = int(_pd)
            et_time = st_time + datetime.timedelta(days=_pd)
            st_datestr = st_time.strftime('%Y%m%d')
            et_datestr = et_time.strftime('%Y%m%d')
            
            all_data = []
            results = {}
            os_data = []
            days = []
            for i in xrange(0,_pd):
                now = datetime.datetime.strptime(st_datestr,'%Y%m%d')
                delta = datetime.timedelta(days=i)  
                n_days = now + delta  
                days.append(n_days.strftime('%Y%m%d'))
            
            xunhuan = [{'name':'All'}]
            
            db = connectMySQL.connMySQL_stat()
            c=db.cursor()
            fanhui = {}
            _table = "stat_local_vv"
            if _bt == "2":
                _dtable = "total"
            else:
                _dtable = "paike"
            for vxunhuan in xrange(len(xunhuan)):
                
                
                sql = "SELECT date,sum(vv),type  FROM `%s` WHERE date >= %s and date < %s and  business_type=%s and pid_stat=1 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL'  and device_type in (%s) and partner_mode in (%s)  group by date,type order by date desc " % (_table,st_datestr,et_datestr,_bt,_osid,_device_type,_pm)
                
                
                sql_z = "SELECT date,sum(vv)  FROM `stat_day_%s_collect` WHERE date >= %s and date < %s and  business_type=%s and pid_stat=1 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL'  and device_type in (%s) and partner_mode in (%s)  group by date " % (_dtable,st_datestr,et_datestr,_bt,_osid,_device_type,_pm)
                
                
                        
                print sql
                c.execute(sql)  
                result_all = c.fetchall()
                
                print sql_z
                c.execute(sql_z)  
                result_z = c.fetchall()
                
                _itt = ['ALL','LS200','LF106','LF_996','LF_997','LF_998','NS200','NF_100','NF_101','NF_102','NF_104','NF_105','NF_106','NF_996','NF_997','NF_998','NF_999','NF400','OTHER']
                
                
                
                days_l = []
                jiriqi = []
                for result in result_all:
                    if str(result[0]) not in jiriqi:
                        jiriqi.append(str(result[0]))
                
                for dv in jiriqi:
                    
                    _riqi = dv
                    _zhilist = []
                    
                    z_all = 0
                    for vvss in result_z:
                        if str(vvss[0]) == _riqi:
                            z_all = int(vvss[1])
                            
                    
                    
                    #print _itt
                    
                    for itv in _itt:
                        shu = 0
                        for rsv in result_all:
                            if _riqi == str(rsv[0]) and str(rsv[2]) == itv:
                                shu = int(rsv[1])
                        _zhilist.append(shu)
                    days_l.append({'days':_riqi,'zhilist':_zhilist,'z_all':z_all})
                    
                #print days_l
                #print xianx
                #生成表格
                
                table = ""
                
                print days_l
                
                for xy in xrange(len(days_l)):
                    if xy % 2 ==0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                    table += "<tr %s><td>%s(%s)</td>" % (bg,cnsort.fordate(days_l[xy]['days'],3),common.getxingqi(days_l[xy]['days']))
                    
                    fxylist = days_l[xy]['zhilist']
                    
                    z_all = days_l[xy]['z_all']
                    
                    #print z_all
                    
                    cha = int(z_all) - int(days_l[xy]['zhilist'][0])
                    
                    #print days_l[xy]['zhilist'][0]
                    
                    jiji = 1
                    for fxy in fxylist:
                        if jiji == 1:
                            table += "<td>%s</td>" % z_all
                        elif jiji == 19:
                            table += "<td>%s</td>" % (fxy+cha)
                        else:
                            table += "<td>%s</td>" % fxy
                            
                        jiji = jiji + 1
                    
                    table +="</tr>"
                table += u"</tbody>"
                
                fv = {}
                
                fv['table'] = table
                
                fanhui[xunhuan[vxunhuan]['name']] = fv
                
            
            c.close()
            db.close()
            _url = hashlib.md5(_url)
            _url.digest()
            try:
                mc.set(_url.hexdigest(),fanhui,1024*1024)
            except:
                pass
        else:
            fanhui = m_value
            
        
        self.write(fanhui)
        self.finish()
        



class PlayDurationMain(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
    
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        _pm = self.get_argument('pm','').strip()
        _items = self.get_argument('items','UV,VV,').strip()
        _items = _items.rstrip(',')
        _items = _items.split(",")
        
        """
        AboutDiv = ""
        for _it in _items:
            if _it in common.AboutVideo:
                AboutDiv += common.AboutVideo[_it]
        """
        
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        m_value = mc.get(_md5.hexdigest()) or {}
        
        #print settings.cache_on
        if settings.cache_on == 0:
            m_value = {}
            #print '123'
        
        m_value = {}
        
        if not m_value:
            
            try:
                st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                return
            
            if not _pd:
                ed_time = datetime.datetime.now()
                delta = ed_time - st_time 
                _pd =  abs(delta.days)
            
            _pd = int(_pd)
            et_time = st_time + datetime.timedelta(days=_pd)
            st_datestr = st_time.strftime('%Y%m%d')
            et_datestr = et_time.strftime('%Y%m%d')
            
            all_data = []
            results = {}
            os_data = []
            days = []
            for i in xrange(0,_pd):
                now = datetime.datetime.strptime(st_datestr,'%Y%m%d')
                delta = datetime.timedelta(days=i)  
                n_days = now + delta  
                days.append(n_days.strftime('%Y%m%d'))
            '''
            if _osid == "":
                xunhuan = [{'name':'All','id':'61,59,52'},{'name':'Android','id':'61'},{'name':'iOS','id':'52'},{'name':'WP7','id':'59'}]
            elif _device_type == "":
                xunhuan = [{'name':'All','id':'1,2'},{'name':'Phone','id':'1'},{'name':'Pad','id':'2'}]
            elif _pm == "":
                xunhuan = [{'name':'All','id':'1,3,2,8'},{'name':'qudao','id':'2,8'},{'name':'changshang','id':'1'}]
            else:
            '''
            
            xunhuan = [{'name':'All'}]
            
            db = connectMySQL.connMySQL_stat()
            c=db.cursor()
            fanhui = {}
            _table = "stat_day_total_collect"
            for vxunhuan in xrange(len(xunhuan)):
                
                
                sql = "SELECT date,sum(play_load_duration),sum(play_load_times)  FROM `%s` WHERE date >= %s and date < %s and  business_type=2 and pid_stat=1 and os_id in (%s) and  ver = 'ALL' and prov = 'ALL' and city = 'ALL'  and device_type in (%s) and partner_mode in (%s)  group by date desc " % (_table,st_datestr,et_datestr,_osid,_device_type,_pm)
                        
                sql_bdur = "  select sum(num),date,time_type from stat_duration_result where duration_type = 2 and date >= %s and date < %s  and  pid_stat=1 and business_type = 2 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and device_type in (%s) and partner_mode in (%s)  group by date,time_type " % (st_datestr,et_datestr,_osid,_device_type,_pm)
                
                c.execute(sql)  
                result_all = c.fetchall()
                
                c.execute(sql_bdur)
                result_bdur = c.fetchall()
                
                
                
                
                b3_all = 0
                b5_all = 0
                b8_all = 0
                b300_all = 0
                b301_all = 0
                
                p3_all = 0
                p5_all = 0
                p8_all = 0
                p300_all = 0
                p301_all = 0
                
                pv_all = 0
                UV_all = 0
                NU_all = 0
                VV_all = 0
                VVUV_all = 0
                Dur_all = 0
                DurVV_all = 0
                DurUV_all = 0
                Comp_all = 0
                CompVV_all = 0
                    
                BefDurTime_all = 0
                PlayDurTime_all = 0
                PlayTimeVV_all = 0
                PlayDurVV_all = 0
                HDSDDurTime_all = 0
                SDHDDurTime_all = 0
                HD2DurTime_all = 0
                RelateAPIAveRespTime_all = 0
                VdDetailAPIAveRespTime_all = 0
                VdUrlAPIAveRespTime_all = 0
                
                days_l = []
                jiriqi = []
                for result in result_all:
                    jiriqi.append(str(result[0]))
                
                
                jcjishu = 0
                for result in result_all:
                    
                    _riqi = str(result[0])
                    
                    b3 = 0
                    b5 = 0
                    b8 = 0
                    b300 = 0
                    b301 = 0
                    
                    for bdurv in result_bdur:
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 3:
                            b3 = int(bdurv[0])
                        
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 5:
                            b5 = int(bdurv[0])
                            
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 8:
                            b8 = int(bdurv[0])
                            
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 300:
                            b300 = int(bdurv[0])
                        
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 301:
                            b301 = int(bdurv[0])
                    
                    
                    
                        
                        
                    before_duration = int(result[1])
                    before_times = int(result[2])
                    
                    #print before_duration,before_times
                        
                    if (before_duration == 0 or before_times == 0):
                        BefDurTime = 0
                    else:
                        BefDurTime = before_duration/before_times/1000
                        
                    BefDurTime = round(BefDurTime,2)
                        
                    
                    
                    try:
                        zhanbib = int(b3) / int(result[2])
                    except:
                        zhanbib = 0
                    b3 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(b5) / int(result[2])
                    except:
                        zhanbib = 0
                    b5 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(b8) / int(result[2])
                    except:
                        zhanbib = 0
                    b8 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(b300) / int(result[2])
                    except:
                        zhanbib = 0
                    b300 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(b301) / int(result[2])
                    except:
                        zhanbib = 0
                    b301 = round(zhanbib,2)
                    
                    days_l.append({'days':_riqi,'BefDurTime':BefDurTime,'b3':b3,'b5':b5,'b3':b3,'b8':b8,'b300':b300,'b301':b301})
                    
                    b3_all += b3
                    b5_all += b5
                    b8_all += b8
                    b300_all += b300
                    b301_all += b301
                    
                #print xianx
                #生成表格
                table = ""
                for xy in xrange(len(days_l)):
                    if xy % 2 ==0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                    table += "<tr %s><td>%s(%s)</td>" % (bg,cnsort.fordate(days_l[xy]['days'],3),common.getxingqi(days_l[xy]['days']))
                    
                    pingjun = days_l[xy]['BefDurTime']
                    
                    table += "<td style='padding:0px;'>"
        
                    
                    nl = str(days_l[xy]['b3']).split(".")
                    #print nl
                    if len(str(nl[1])) < 4:
                        shu = "%s0%s" % (days_l[xy]['b3'] * 100,"%")
                    else:
                        shu = "%s%s" % (days_l[xy]['b3'] * 100,"%")
                    b3 = shu
                    
                    #print b3
                    
                    
                    
                    nl = str(days_l[xy]['b5']).split(".")
                    #print nl
                    if len(str(nl[1])) < 4:
                        shu = "%s0%s" % (days_l[xy]['b5'] * 100,"%")
                    else:
                        shu = "%s%s" % (days_l[xy]['b5'] * 100,"%")
                    b5 = shu
                    
                    
                    nl = str(days_l[xy]['b8']).split(".")
                    #print nl
                    if len(str(nl[1])) < 4:
                        shu = "%s0%s" % (days_l[xy]['b8'] * 100,"%")
                    else:
                        shu = "%s%s" % (days_l[xy]['b8'] * 100,"%")
                    b8 = shu
                    
                   
                    nl = str(days_l[xy]['b300']).split(".")
                    #print nl
                    if len(str(nl[1])) < 4:
                        shu = "%s0%s" % (days_l[xy]['b300'] * 100,"%")
                    else:
                        shu = "%s%s" % (days_l[xy]['b300'] * 100,"%")
                    b300 = shu
                    
                    nl = str(days_l[xy]['b301']).split(".")
                    #print nl
                    if len(str(nl[1])) < 4:
                        shu = "%s0%s" % (days_l[xy]['b301'] * 100,"%")
                    else:
                        shu = "%s%s" % (days_l[xy]['b301'] * 100,"%")
                    b301 = shu
                    
                    table += "<div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div></td>" % (pingjun,b3,b5,b8,b300,b301)
                    
                    table +="</tr>"
                table += u"</tbody><tfoot>"
                
                fv = {}
                
                fv['table'] = table
                
                fanhui[xunhuan[vxunhuan]['name']] = fv
                
            
            c.close()
            db.close()
            _url = hashlib.md5(_url)
            _url.digest()
            try:
                mc.set(_url.hexdigest(),fanhui,1024*1024)
            except:
                pass
        else:
            fanhui = m_value
        self.write(fanhui)
        self.finish()




        
class NewMainPaike(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        _dao = self.get_argument('dao','asc').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        _pm = self.get_argument('pm','').strip()
        _items = self.get_argument('items','UV,VV,').strip()
        _items = _items.rstrip(',')
        _items = _items.split(",")
        
        
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        m_value = mc.get(_md5.hexdigest()) or {}
        if settings.cache_on == 0:
            m_value = {}
        #print m_value
        
        if not m_value:
        
        
            
            try:
                st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                return
            
            if not _pd:
                ed_time = datetime.datetime.now()
                delta = ed_time - st_time 
                _pd =  abs(delta.days)
            
            _pd = int(_pd)
            et_time = st_time + datetime.timedelta(days=_pd)
            st_datestr = st_time.strftime('%Y%m%d')
            et_datestr = et_time.strftime('%Y%m%d')
            
            all_data = []
            results = {}
            os_data = []
            days = []
            for i in xrange(0,_pd):
                now = datetime.datetime.strptime(st_datestr,'%Y%m%d')
                delta = datetime.timedelta(days=i)  
                n_days = now + delta  
                days.append(n_days.strftime('%Y%m%d'))

            if _osid == "":
                xunhuan = [{'name':'All','id':'61,52','tid':'-1'},{'name':'Android','id':'61','tid':'61'},{'name':'iOS','id':'52','tid':'52'}]
            elif _device_type == "":
                xunhuan = [{'name':'All','id':'1','tid':'1'},{'name':'Phone','id':'1','tid':'1'}]
            elif _pm == "":
                xunhuan = [{'name':'All','id':'1,3,2,8','tid':'-1'},{'name':'qudao','id':'2,8','tid':'28'},{'name':'changshang','id':'1','tid':'1'}]
            else:
                xunhuan = [{'name':'All'}]
            
            db = connectMySQL.connMySQL_stat()
            c=db.cursor()
            fanhui = {}
            _table = "stat_day_paike_collect"
            for vxunhuan in xrange(len(xunhuan)):
                
                
                if _pm != "":
                    _pmsql = " and partner_mode in (%s) " % _pm
                else:
                    _pmsql = " "
                tihuanriqi = "tihuanriqi"
                if _osid == "":
                    if _osid == "" and _device_type == "" and _pm == "":
                        sql = " SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(upload),sum(register),sum(total_uploads)  FROM `%s` WHERE date >= %s and date < %s  and  business_type=4 and pid_stat=1 and os_id in (%s) and device_type in (1) and partner_mode in (1,2,3,8) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' %s group by date order by date %s " % (_table,st_datestr,et_datestr,xunhuan[vxunhuan]['id'],common.clear_date(),_dao)
                        sql_resp = " SELECT pid  FROM `%s` WHERE date = %s and  business_type=4 and pid_stat=1 and os_id in (%s) and device_type in (1) and partner_mode in (1,2,3,8) and ver = 'ALL' and prov = 'ALL' and city = 'ALL'  " % (_table,tihuanriqi,xunhuan[vxunhuan]['id'])
                        
                        
                        sql_tu = " SELECT sum(total_user),date FROM `stat_day_user` WHERE app_type = 2 and os_id  = %s  and  device_type  = -1 group by date " % (xunhuan[vxunhuan]['tid'])
                        
                    elif _osid == "" and _device_type != "":
                        sql = "SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(upload),sum(register),sum(total_uploads)  FROM `%s` WHERE date >= %s and date < %s and  business_type=4 and pid_stat=1 and os_id in (%s) and  ver = 'ALL' and prov = 'ALL' and city = 'ALL'  and device_type in (%s) %s    %s   group by date order by date %s " % (_table,st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type,_pmsql,common.clear_date(),_dao)
                        sql_resp = "SELECT pid  FROM `%s` WHERE date = %s  and  business_type=4 and pid_stat=1 and os_id in (%s) and  ver = 'ALL' and prov = 'ALL' and city = 'ALL'  and device_type in (%s) %s   " % (_table,tihuanriqi,xunhuan[vxunhuan]['id'],_device_type,_pmsql)
                        
                        
                        sql_tu = " SELECT sum(total_user),date FROM `stat_day_user` WHERE app_type = 2 and os_id  = %s  and  device_type  = %s group by date " % (xunhuan[vxunhuan]['tid'],_device_type)
                        
                    elif _osid == "" and _device_type == "":
                        sql = "SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(upload),sum(register),sum(total_uploads)  FROM `%s` WHERE date >= %s and date < %s and  business_type=4 and pid_stat=1 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and device_type in (1,2) %s     %s  group by date order by date %s " % (_table,st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_pmsql,common.clear_date(),_dao)
                        sql_resp = "SELECT pid  FROM `%s` WHERE date = %s and  business_type=4 and pid_stat=1 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and device_type in (1,2) %s  " % (_table,tihuanriqi,xunhuan[vxunhuan]['id'],_pmsql)
                        
                        
                        sql_tu = " SELECT sum(total_user),date FROM `stat_day_user` WHERE app_type = 2 and os_id  = %s  and  device_type  = -1 group by date " % (xunhuan[vxunhuan]['tid'])
                        
                elif _device_type == "":
                        sql = " SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(upload),sum(register),sum(total_uploads)  FROM `%s` WHERE date >= %s and date < %s and  business_type=4 and pid_stat=1 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and device_type in (%s) %s  %s  group by date order by date %s " % (_table,st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'],_pmsql,common.clear_date(),_dao)
                        sql_resp = " SELECT pid  FROM `%s` WHERE date = %s  and  business_type=4 and pid_stat=1 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and device_type in (%s) %s  " % (_table,tihuanriqi,_osid,xunhuan[vxunhuan]['id'],_pmsql)
                        
                        sql_tu = " SELECT sum(total_user),date FROM `stat_day_user` WHERE app_type = 2 and os_id  = %s  and  device_type  = %s group by date " % (_osid,xunhuan[vxunhuan]['tid'])
                        
                elif _pm == "":
                        sql = " SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(upload),sum(register),sum(total_uploads)  FROM `%s` WHERE date >= %s and date < %s and  business_type=4 and pid_stat=1 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and  device_type in (%s) and partner_mode in (%s)  %s   group by date order by date %s " % (_table,st_datestr,et_datestr,_osid,_device_type,xunhuan[vxunhuan]['id'],common.clear_date(),_dao)
                        sql_resp = " SELECT pid  FROM `%s` WHERE date = %s  and  business_type=4 and pid_stat=1 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and  device_type in (%s) and partner_mode in (%s)   " % (_table,tihuanriqi,_osid,_device_type,xunhuan[vxunhuan]['id'])
                        
                        sql_tu = " SELECT sum(total_user),date FROM `stat_day_user` WHERE app_type = 2 and os_id  = %s  and  device_type  = %s group by date " % (_osid,_device_type)
                        
                        
                else:
                        sql = "SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(upload),sum(register),sum(total_uploads)  FROM `%s` WHERE date >= %s and date < %s and  business_type=4 and pid_stat=1 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and   device_type in (%s) and partner_mode in (%s)   %s  group by date order by date %s " % (_table,st_datestr,et_datestr,_osid,_device_type,_pm,common.clear_date(),_dao)
                        
                        sql_tu = " SELECT sum(total_user),date FROM `stat_day_user` WHERE app_type = 2 and os_id  = %s  and  device_type  = %s group by date " % (_osid,_device_type)
                        
                        sql_resp = "SELECT pid  FROM `%s` WHERE date = %s  and  business_type=4 and pid_stat=1 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and   device_type in (%s) and partner_mode in (%s)  " % (_table,tihuanriqi,_osid,_device_type,_pm)
                #print sql
                c.execute(sql)  
                result_all = c.fetchall()
                
                if "TU" in _items:
                    c.execute(sql_tu)
                    result_tu = c.fetchall()
                else:
                    result_tu = []
                
                TU_list = []
                UV_list = []
                pv_list = []
                NU_list = []
                VV_list = []
                VVUV_list = []
                SU_list = []
                FU_list = []
                NR_list = []
                hd_list = []
                sd_list = []
                transcodetime_list = []
                
                c01_list = []
                c12_list = []
                c23_list = []
                c34_list = []
                c45_list = []
                c5_list = []
                hd2_list = []
                
                
                
                pv_all = 0
                TU_all = 0
                UV_all = 0
                NU_all = 0
                FU_all = 0
                VV_all = 0
                VVUV_all = 0
                SU_all = 0
                NR_all = 0
                hd_all = 0
                sd_all = 0
                hd2_all = 0
                transcodetime_all = 0
                
                c01_all = 0
                c12_all = 0
                c23_all = 0
                c34_all = 0
                c45_all = 0
                c5_all = 0
                
                days_l = []
                jiriqi = []
                for result in result_all:
                    jiriqi.append(str(result[0]))
                
                
                jcjishu = 0
                for result in result_all:
                    
                    
                    
                    
                    
                    _riqi = str(result[0])
                    
                    
                    
                    TU = 0
                    
                    for tuv in result_tu:
                        if _riqi == str(tuv[1]):
                            TU = int(tuv[0])
                    
                    
                    
                    pv = int(result[3])
                    UV = int(result[4])
                    VV = int(result[5])
                    try:
                        VVUV = VV / UV
                    except:
                        VVUV = 0
                    
                    VVUV = round(VVUV,2)
                    NU = int(result[6])
                    SU = int(result[8])
                    TU = int(result[10])
                    FU = TU - SU
                    if FU < 0:
                        FU = 0
                    
                    NR = int(result[9])
                    
                    cha = 0
                    _xunyao_ziduan = ['transcodetime','sd','hd','hd2','c01','c12','c23','c34','c45','c5']
                    
                    cha = len(set(_items) & set(_xunyao_ziduan))
                                
                    if cha != 0:
                    
                        if jcjishu == 0:
                            sql_resp = sql_resp.replace("tihuanriqi",str(result[0]))
                        else:
                            sql_resp = sql_resp.replace(jiriqi[jcjishu-1],str(result[0]))

                        c.execute(sql_resp)  
                        pids_list = c.fetchall()
                        pids_str = ""
                        for pids_list_value in pids_list:
                            pids_str += "'%s'," % pids_list_value
                        pids = pids_str.rstrip(",")
                        
                        if pids == "":
                            pids = "'123'"
                        
                        _riqi_start = "%s %s" % (_riqi,"00:00:00")
                        d1 = datetime.datetime.strptime(_riqi_start, '%Y%m%d %H:%M:%S')
                        chuo1 = long(time.mktime(d1.timetuple()))
                        
                        _riqi_end = "%s %s" % (_riqi,"23:59:59")
                        d2 = datetime.datetime.strptime(_riqi_end, '%Y%m%d %H:%M:%S')
                        chuo2 = long(time.mktime(d2.timetuple()))
                        
                        sql = " select sum(transcodetime) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) limit 1 " % (chuo1,chuo2,pids) 
                        #print sql
                        c.execute(sql)  
                        res = c.fetchone()
                        
                        if res[0] != None: 
                            zong = res[0]
                        else:
                            zong = 0
                        
                        sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and transcodetime != 0 limit 1 " % (chuo1,chuo2,pids)
                        #print sql
                        c.execute(sql)  
                        res = c.fetchone()
                        geshu = res[0]
                        
                        
                        if zong == 0 or geshu == 0:
                             transcodetime = 0
                        else:
                            transcodetime = zong / geshu

                        transcodetime = round(transcodetime,2)
                        
                        sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and quality = 'sd' limit 1  " % (chuo1,chuo2,pids) 
                        #print sql
                        c.execute(sql)  
                        res = c.fetchone()
                        sd = res[0]
                        
                            
                        sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and quality = 'hd2' limit 1 " % (chuo1,chuo2,pids)
                        #print sql 
                        c.execute(sql)  
                        res = c.fetchone()
                        hd2 = res[0]
                        
                            
                        sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and quality = 'hd' limit 1 " % (chuo1,chuo2,pids) 
                        #print sql
                        c.execute(sql)  
                        res = c.fetchone()
                        hd = res[0]
                        
                            
                        sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and duration > 0 and duration < 60 limit 1 " % (chuo1,chuo2,pids) 
                        #print sql
                        c.execute(sql)  
                        res = c.fetchone()
                        c01 = res[0]
                       
                        
                        sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and duration >= 60 and duration < 120 limit 1 " % (chuo1,chuo2,pids) 
                        #print sql
                        c.execute(sql)  
                        res = c.fetchone()
                        c12 = res[0]
                        
                        
                        sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and duration >= 120 and duration < 180 limit 1 " % (chuo1,chuo2,pids) 
                        #print sql
                        c.execute(sql)  
                        res = c.fetchone()
                        c23 = res[0]
                        
                        
                        sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and duration >= 180 and duration < 240 limit 1 " % (chuo1,chuo2,pids) 
                        #print sql
                        c.execute(sql)  
                        res = c.fetchone()
                        c34 = res[0]
                        
                        
                        sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and duration >= 240 and duration < 300 limit 1 " % (chuo1,chuo2,pids) 
                        #print sql
                        c.execute(sql)  
                        res = c.fetchone()
                        c45 = res[0]
                        
                        
                        sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and duration >= 300 limit 1 " % (chuo1,chuo2,pids) 
                        #print sql
                        c.execute(sql)  
                        res = c.fetchone()
                        c5 = res[0]
                    else:
                        transcodetime = round(0,2)
                        sd = 0
                        hd2 = 0
  
                        hd = 0

                        c01 = 0

                        c12 = 0

                        c23 = 0

                        c34 = 0

                        c45 = 0

                        c5 = 0

                    
                    TU_list.append(str(TU))
                    UV_list.append(str(UV))
                    pv_list.append(str(pv))
                    NU_list.append(str(NU))
                    VV_list.append(str(VV))
                    VVUV_list.append(str(VVUV))
                    
                    SU_list.append(str(SU))
                    FU_list.append(str(FU))
                    
                    NR_list.append(str(NR))
                    
                    transcodetime_list.append(str(transcodetime))
                    sd_list.append(str(sd))
                    hd2_list.append(str(hd2))
                    hd_list.append(str(hd))
                    
                    c01_list.append(str(c01))
                    c12_list.append(str(c12))
                    
                    c23_list.append(str(c23))
                    c34_list.append(str(c34))
                    c45_list.append(str(c45))
                    c5_list.append(str(c5))
                    

                    
                    days_l.append({'days':_riqi,'pv':pv,'UV':UV,'VV':VV,'NU':NU,'VVUV':VVUV,'SU':SU,'NR':NR,'transcodetime':transcodetime,'hd':hd,'sd':sd,'c01':c01,'c12':c12,'c23':c23,'c34':c34,'c45':c45,'c5':c5,'hd2':hd2,'FU':FU,'TU':TU})
                    
                    
                    pv_all += pv
                    TU_all += TU
                    UV_all += UV
                    NU_all += NU
                    VV_all += VV
                    VVUV_all += VVUV
                    
                    SU_all += SU
                    FU_all += FU
                    
                    NR_all += NR
                    
                    transcodetime_all += transcodetime
                    sd_all += sd
                    hd_all += hd
                    hd2_all += hd2
                    
                    c01_all += c01
                    c12_all += c12
                    
                    c23_all += c23
                    c34_all += c34
                    c45_all += c45
                    c5_all += c5
                    
                    
                    jcjishu = jcjishu + 1
                
                #print eval("%s%s" % ('UV','_all'))
                #print days_l
                #生成线性图
                
                xianx = "["
                
                for xy in xrange(len(days_l)):
                    yy = days_l[xy]['days'][0:4]
                    mm = days_l[xy]['days'][4:6]
                    dd = days_l[xy]['days'][6:]
                    xianx += "'%s/%s/%s'," % (yy,mm,dd)
                xianx += "]" 
                
                xiany = "["
                for items_value in _items:
                    shuzu = eval("%s%s" % (items_value,'_list'))
                    shuzu_str = ",".join(shuzu)
                    qiangzu = []
                    qiangzu.append(items_value)
                    mingzi = cnsort.valueFullNameArr(qiangzu)
                    #xiany += "{name: '%s',data: [%s]}," % (mingzi[0],shuzu_str)
                    xiany += "[%s]," % (shuzu_str)            
                xiany += "]"                
                #print xianx
                #生成表格
                table = ""
                for xy in xrange(len(days_l)):
                    if xy % 2 ==0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                    table += "<tr %s><td>%s(%s)</td>" % (bg,cnsort.fordate(days_l[xy]['days'],3),common.getxingqi(days_l[xy]['days']))
                    
                    for items_value in _items:
                        table += cnsort.genTableResultInc3(days_l[xy-1].get(items_value),days_l[xy].get(items_value),items_value,xy,days_l)
                    table +="</tr>"
                #生成合计
                table += u"</tbody><tfoot><tr><th class='new_silver_first_n footer'>合计</th>"
                for items_value in _items:
                        if cnsort.checkValueMode(items_value):
                            shu = eval("%s%s" % (items_value,'_all'))
                            
                            if items_value == "CompVV":
                                try:
                                    shu = shu / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    table += "<th style=\"text-align:right;\" class=\"footer\">%s0%%</th>" % (shu*100)
                                else:
                                    table += "<th style=\"text-align:right;\" class=\"footer\">%s%%</th>" % (shu*100)
                            else:
                                try:
                                    shu = shu / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,2)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 2:
                                    table += "<th style=\"text-align:right;\" class=\"footer\">%s0</th>" % shu
                                else:
                                    table += "<th style=\"text-align:right;\" class=\"footer\">%s</th>" % shu
                        else:
                            shu = eval("%s%s" % (items_value,'_all'))
                            table += "<th style=\"text-align:right;\" class=\"footer\">%s</th>" % cnsort.num2money(shu)
                
                table += "</tr>"
                
                zongzong = {}
                zongzong['day'] = len(days_l)
                zongzong['TU_all'] = TU_all
                zongzong['pv_all'] = pv_all
                zongzong['UV_all'] = UV_all
                zongzong['VV_all'] = VV_all
                zongzong['NU_all'] = NU_all
                zongzong['VVUV_all'] = VVUV_all
                
                zongzong['SU_all'] = SU_all
                zongzong['FU_all'] = FU_all
                zongzong['NR_all'] = NR_all
                
                zongzong['transcodetime_all'] = transcodetime_all
                zongzong['sd_all'] = sd_all
                zongzong['hd_all'] = hd_all
                zongzong['hd2_all'] = hd2_all
                
                zongzong['c01_all'] = c01_all
                zongzong['c12_all'] = c12_all
                zongzong['c23_all'] = c23_all
                zongzong['c34_all'] = c34_all
                zongzong['c45_all'] = c45_all
                zongzong['c5_all'] = c5_all
               
                
                fv = {}
                
                fv['table'] = table
                fv['zongzong'] = zongzong
                fv['xianx'] = xianx
                fv['xiany'] = xiany
                
                fanhui[xunhuan[vxunhuan]['name']] = fv
                
            #生成饼图
            blist = ['UV','VV','NU','SU','NR','hd','sd','c01','c12','c23','c34','c45','c5','hd2','FU']
            if _osid == "":
                fc = {}
                for blist_value in blist:
                    kvalue = "%s%s" % (blist_value,'_all')
                    _android = fanhui['Android']['zongzong'][kvalue]
                    _ios = fanhui['iOS']['zongzong'][kvalue]
                    dd = "[['Android',%s],['Ios',%s]]" % (_android,_ios)
                    fc[blist_value] = dd 
            elif _device_type == "":
                fc = {}
                for blist_value in blist:
                    kvalue = "%s%s" % (blist_value,'_all')
                    _phone = fanhui['Phone']['zongzong'][kvalue]
                    dd = "[['Phone',%s]]" % _phone
                    fc[blist_value] = dd 
            elif _pm == "":
                fc = {}
                for blist_value in blist:
                    kvalue = "%s%s" % (blist_value,'_all')
                    _changshang = fanhui['changshang']['zongzong'][kvalue]
                    _qudao = fanhui['qudao']['zongzong'][kvalue]
                    dd = u"[['厂商内置',%s],['渠道推广',%s]]" % (_changshang,_qudao)
                    fc[blist_value] = dd
            else:
                fc = '123'
            fanhui['All']['bingtu'] = fc
                
            c.close()
            db.close()
            _url = hashlib.md5(_url)
            _url.digest()
            try:
                mc.set(_url.hexdigest(),fanhui,1024*1024)
            except:
                pass
        else:
            fanhui = m_value
        self.write(fanhui)
        self.finish()
        
        

class ReturnPaikeTable(BaseHandler):
    def get(self): 
        
        _time = self.get_argument('staDate', '2012/05/01').strip()
        _pd = self.get_argument('pd','3').strip()
        _dao = self.get_argument('dao','desc').strip()
        _format = self.get_argument('format',';').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        _pm = self.get_argument('pm','').strip()
        _items = self.get_argument('items','UV,VV,NU,VVUV,NR,SU,FU,transcodetime,sd,hd,hd2,c01,c12,c23,c34,c45,c5,').strip()
        _items = _items.rstrip(',')
        _items = _items.split(",")
        
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        m_value = mc.get(_md5.hexdigest()) or {}
        
        
        if _format == ";":
        
            rtable = "\"Date\";\"UV\";\"VV\";\"NU\";\"VV/UV\";\"NewRegister\";\"SuccedUpload\";\"FailedUpload\";\"Transcodetime(s)\";\"sd\";\"hd\";\"hd2\";\"0-1min\";\"1-2min\";\"2-3min\";\"3-4min\";\"4-5min\";\">5min\"\n"
        else:
            rtable = "\"Date\",\"UV\",\"VV\",\"NU\",\"VV/UV\",\"NewRegister\",\"SuccedUpload\",\"FailedUpload\",\"Transcodetime(s)\",\"sd\",\"hd\",\"hd2\",\"0-1min\",\"1-2min\",\"2-3min\",\"3-4min\",\"4-5min\",\">5min\"\n"
        
        
        #if settings.cache_on == 0:
        m_value = {}
        #print m_value
        
        
        if not m_value:
        
            
            try:
                st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                return
            
            if not _pd:
                ed_time = datetime.datetime.now()
                delta = ed_time - st_time 
                _pd =  abs(delta.days)
            
            _pd = int(_pd)
            et_time = st_time + datetime.timedelta(days=_pd)
            st_datestr = st_time.strftime('%Y%m%d')
            et_datestr = et_time.strftime('%Y%m%d')
            
            all_data = []
            results = {}
            os_data = []
            days = []
            for i in xrange(0,_pd):
                now = datetime.datetime.strptime(st_datestr,'%Y%m%d')
                delta = datetime.timedelta(days=i)  
                n_days = now + delta  
                days.append(n_days.strftime('%Y%m%d'))

            if _osid == "":
                xunhuan = [{'name':'All','id':'61,52'}]
            elif _device_type == "":
                xunhuan = [{'name':'All','id':'1'}]
            elif _pm == "":
                xunhuan = [{'name':'All','id':'1,3,2,8'}]
            else:
                xunhuan = [{'name':'All'}]
            
            db = connectMySQL.connMySQL_stat()
            c=db.cursor()
            fanhui = {}
            _table = "stat_day_paike"
            for vxunhuan in xrange(len(xunhuan)):
                
                
                if _pm != "":
                    _pmsql = " and partner_mode in (%s) " % _pm
                else:
                    _pmsql = " "
                tihuanriqi = "tihuanriqi"
                if _osid == "":
                    if _osid == "" and _device_type == "" and _pm == "":
                        sql = " SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(upload),sum(register),sum(total_uploads)  FROM `%s` WHERE date >= %s and date < %s  and  business_type=4 and pid_stat=1 and os_id in (%s) and device_type in (1) and partner_mode in (1,2,3,8) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' group by date order by date %s " % (_table,st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_dao)
                        sql_resp = " SELECT pid  FROM `%s` WHERE date = %s and  business_type=4 and pid_stat=1 and os_id in (%s) and device_type in (1) and partner_mode in (1,2,3,8) and ver = 'ALL' and prov = 'ALL' and city = 'ALL'  " % (_table,tihuanriqi,xunhuan[vxunhuan]['id'])
                    elif _osid == "" and _device_type != "":
                        sql = "SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(upload),sum(register),sum(total_uploads)  FROM `%s` WHERE date >= %s and date < %s and  business_type=4 and pid_stat=1 and os_id in (%s) and  ver = 'ALL' and prov = 'ALL' and city = 'ALL'  and device_type in (%s) %s  group by date order by date %s " % (_table,st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type,_pmsql,_dao)
                        sql_resp = "SELECT pid  FROM `%s` WHERE date = %s  and  business_type=4 and pid_stat=1 and os_id in (%s) and  ver = 'ALL' and prov = 'ALL' and city = 'ALL'  and device_type in (%s) %s   " % (_table,tihuanriqi,xunhuan[vxunhuan]['id'],_device_type,_pmsql)
                    elif _osid == "" and _device_type == "":
                        sql = "SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(upload),sum(register),sum(total_uploads)  FROM `%s` WHERE date >= %s and date < %s and  business_type=4 and pid_stat=1 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and device_type in (1,2) %s  group by date order by date %s " % (_table,st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_pmsql,_dao)
                        sql_resp = "SELECT pid  FROM `%s` WHERE date = %s and  business_type=4 and pid_stat=1 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and device_type in (1,2) %s  " % (_table,tihuanriqi,xunhuan[vxunhuan]['id'],_pmsql)
                        
                elif _device_type == "":
                        sql = " SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(upload),sum(register),sum(total_uploads)  FROM `%s` WHERE date >= %s and date < %s and  business_type=4 and pid_stat=1 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and device_type in (%s) %s  group by date order by date %s " % (_table,st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'],_pmsql,_dao)
                        sql_resp = " SELECT pid  FROM `%s` WHERE date = %s  and  business_type=4 and pid_stat=1 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and device_type in (%s) %s  " % (_table,tihuanriqi,_osid,xunhuan[vxunhuan]['id'],_pmsql)
                elif _pm == "":
                        sql = " SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(upload),sum(register),sum(total_uploads)  FROM `%s` WHERE date >= %s and date < %s and  business_type=4 and pid_stat=1 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and  device_type in (%s) and partner_mode in (%s)   group by date order by date %s " % (_table,st_datestr,et_datestr,_osid,_device_type,xunhuan[vxunhuan]['id'],_dao)
                        sql_resp = " SELECT pid  FROM `%s` WHERE date = %s  and  business_type=4 and pid_stat=1 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and  device_type in (%s) and partner_mode in (%s)   " % (_table,tihuanriqi,_osid,_device_type,xunhuan[vxunhuan]['id'])
                else:
                        sql = "SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(upload),sum(register),sum(total_uploads)  FROM `%s` WHERE date >= %s and date < %s and  business_type=4 and pid_stat=1 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and   device_type in (%s) and partner_mode in (%s)   group by date order by date %s " % (_table,st_datestr,et_datestr,_osid,_device_type,_pm,_dao)
                        sql_resp = "SELECT pid  FROM `%s` WHERE date = %s  and  business_type=4 and pid_stat=1 and os_id in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' and   device_type in (%s) and partner_mode in (%s)  " % (_table,tihuanriqi,_osid,_device_type,_pm)
                #print sql
                c.execute(sql)  
                result_all = c.fetchall()
                
                UV_list = []
                pv_list = []
                NU_list = []
                VV_list = []
                VVUV_list = []
                SU_list = []
                FU_list = []
                NR_list = []
                hd_list = []
                sd_list = []
                transcodetime_list = []
                
                c01_list = []
                c12_list = []
                c23_list = []
                c34_list = []
                c45_list = []
                c5_list = []
                hd2_list = []
                
                
                
                pv_all = 0
                UV_all = 0
                NU_all = 0
                FU_all = 0
                VV_all = 0
                VVUV_all = 0
                SU_all = 0
                NR_all = 0
                hd_all = 0
                sd_all = 0
                hd2_all = 0
                transcodetime_all = 0
                
                c01_all = 0
                c12_all = 0
                c23_all = 0
                c34_all = 0
                c45_all = 0
                c5_all = 0
                
                days_l = []
                jiriqi = []
                for result in result_all:
                    jiriqi.append(str(result[0]))
                
                
                jcjishu = 0
                for result in result_all:
                    
                    _riqi = str(result[0])
                    pv = int(result[3])
                    UV = int(result[4])
                    VV = int(result[5])
                    try:
                        VVUV = VV / UV
                    except:
                        VVUV = 0
                    
                    VVUV = round(VVUV,2)
                    NU = int(result[6])
                    SU = int(result[8])
                    TU = int(result[10])
                    FU = TU - SU
                    if FU < 0:
                        FU = 0
                    
                    NR = int(result[9])
                    
                    
                    if jcjishu == 0:
                        sql_resp = sql_resp.replace("tihuanriqi",str(result[0]))
                    else:
                        sql_resp = sql_resp.replace(jiriqi[jcjishu-1],str(result[0]))

                    c.execute(sql_resp)  
                    pids_list = c.fetchall()
                    pids_str = ""
                    for pids_list_value in pids_list:
                        pids_str += "'%s'," % pids_list_value
                    pids = pids_str.rstrip(",")
                    
                    if pids == "":
                        pids = "'123'"
                    
                    _riqi_start = "%s %s" % (_riqi,"00:00:00")
                    d1 = datetime.datetime.strptime(_riqi_start, '%Y%m%d %H:%M:%S')
                    chuo1 = long(time.mktime(d1.timetuple()))
                    
                    _riqi_end = "%s %s" % (_riqi,"23:59:59")
                    d2 = datetime.datetime.strptime(_riqi_end, '%Y%m%d %H:%M:%S')
                    chuo2 = long(time.mktime(d2.timetuple()))
                    
                    sql = " select sum(transcodetime) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) " % (chuo1,chuo2,pids) 
                    #print sql
                    c.execute(sql)  
                    res = c.fetchone()
                    
                    if res[0] != None: 
                        zong = res[0]
                    else:
                        zong = 0
                    
                    sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and transcodetime != 0 " % (chuo1,chuo2,pids)
                    #print sql
                    c.execute(sql)  
                    res = c.fetchone()
                    geshu = res[0]
                    
                    
                    if zong == 0 or geshu == 0:
                         transcodetime = 0
                    else:
                        transcodetime = zong / geshu

                    transcodetime = round(transcodetime,2)
                    
                    sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and quality = 'sd'  " % (chuo1,chuo2,pids) 
                    #print sql
                    c.execute(sql)  
                    res = c.fetchone()
                    sd = res[0]
                    
                        
                    sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and quality = 'hd2'  " % (chuo1,chuo2,pids)
                    #print sql 
                    c.execute(sql)  
                    res = c.fetchone()
                    hd2 = res[0]
                    
                        
                    sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and quality = 'hd'  " % (chuo1,chuo2,pids) 
                    #print sql
                    c.execute(sql)  
                    res = c.fetchone()
                    hd = res[0]
                    
                        
                    sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and duration > 0 and duration < 60  " % (chuo1,chuo2,pids) 
                    #print sql
                    c.execute(sql)  
                    res = c.fetchone()
                    c01 = res[0]
                   
                    
                    sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and duration >= 60 and duration < 120  " % (chuo1,chuo2,pids) 
                    #print sql
                    c.execute(sql)  
                    res = c.fetchone()
                    c12 = res[0]
                    
                    
                    sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and duration >= 120 and duration < 180  " % (chuo1,chuo2,pids) 
                    #print sql
                    c.execute(sql)  
                    res = c.fetchone()
                    c23 = res[0]
                    
                    
                    sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and duration >= 180 and duration < 240  " % (chuo1,chuo2,pids) 
                    #print sql
                    c.execute(sql)  
                    res = c.fetchone()
                    c34 = res[0]
                    
                    
                    sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and duration >= 240 and duration < 300  " % (chuo1,chuo2,pids) 
                    #print sql
                    c.execute(sql)  
                    res = c.fetchone()
                    c45 = res[0]
                    
                    
                    sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and duration >= 300  " % (chuo1,chuo2,pids) 
                    #print sql
                    c.execute(sql)  
                    res = c.fetchone()
                    c5 = res[0]
                    
                    
                    UV_list.append(str(UV))
                    pv_list.append(str(pv))
                    NU_list.append(str(NU))
                    VV_list.append(str(VV))
                    VVUV_list.append(str(VVUV))
                    
                    SU_list.append(str(SU))
                    FU_list.append(str(FU))
                    
                    NR_list.append(str(NR))
                    
                    transcodetime_list.append(str(transcodetime))
                    sd_list.append(str(sd))
                    hd2_list.append(str(hd2))
                    hd_list.append(str(hd))
                    
                    c01_list.append(str(c01))
                    c12_list.append(str(c12))
                    
                    c23_list.append(str(c23))
                    c34_list.append(str(c34))
                    c45_list.append(str(c45))
                    c5_list.append(str(c5))
                    

                    
                    days_l.append({'days':_riqi,'pv':pv,'UV':UV,'VV':VV,'NU':NU,'VVUV':VVUV,'SU':SU,'NR':NR,'transcodetime':transcodetime,'hd':hd,'sd':sd,'c01':c01,'c12':c12,'c23':c23,'c34':c34,'c45':c45,'c5':c5,'hd2':hd2,'FU':FU})
                    
                    
                    pv_all += pv
                    UV_all += UV
                    NU_all += NU
                    VV_all += VV
                    VVUV_all += VVUV
                    
                    SU_all += SU
                    FU_all += FU
                    
                    NR_all += NR
                    
                    transcodetime_all += transcodetime
                    sd_all += sd
                    hd_all += hd
                    hd2_all += hd2
                    
                    c01_all += c01
                    c12_all += c12
                    
                    c23_all += c23
                    c34_all += c34
                    c45_all += c45
                    c5_all += c5
                    
                    
                    jcjishu = jcjishu + 1
                
                #print eval("%s%s" % ('UV','_all'))
                #print days_l
                               
                #print xianx
                #生成表格
                table = ""
                for xy in xrange(len(days_l)):
                    if xy % 2 ==0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                    table += "<tr %s><td>%s(%s)</td>" % (bg,cnsort.fordate(days_l[xy]['days'],3),common.getxingqi(days_l[xy]['days']))
                    rtable += "\"%s\"%s" % (cnsort.fordate(days_l[xy]['days'],3),_format)
                    
                    for items_value in _items:
                        table += cnsort.genTableResultInc3(days_l[xy-1].get(items_value),days_l[xy].get(items_value),items_value,xy,days_l)
                        rtable += common.genTableResultInc3(days_l[xy-1].get(items_value),days_l[xy].get(items_value),items_value,xy,_format)
                    table +="</tr>"
                    rtable = rtable.lstrip(_format)
                    rtable += "\n"
                #生成合计
                table += u"</tbody><tfoot><tr><th class='new_silver_first_n footer'>合计</th>"
                rtable += "\"Total\"%s" % _format
                for items_value in _items:
                        if cnsort.checkValueMode(items_value):
                            shu = eval("%s%s" % (items_value,'_all'))
                            
                            if items_value == "CompVV":
                                try:
                                    shu = shu / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    table += "<th style=\"text-align:right;\" class=\"footer\">%s0%%</th>" % (shu*100)
                                    rtable += "\"%s0%%\"%s" % ((shu*100),_format)
                                else:
                                    table += "<th style=\"text-align:right;\" class=\"footer\">%s%%</th>" % (shu*100)
                                    rtable += "\"%s%%\"%s" % ((shu*100),_format)
                            else:
                                try:
                                    shu = shu / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,2)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 2:
                                    table += "<th style=\"text-align:right;\" class=\"footer\">%s0</th>" % shu
                                    rtable += "\"%s0\"%s" % (shu,_format)
                                else:
                                    table += "<th style=\"text-align:right;\" class=\"footer\">%s</th>" % shu
                                    rtable += "\"%s\"%s" % (shu,_format)
                        else:
                            shu = eval("%s%s" % (items_value,'_all'))
                            table += "<th style=\"text-align:right;\" class=\"footer\">%s</th>" % cnsort.num2money(shu)
                            rtable += "\"%s\"%s" % (cnsort.num2money(shu),_format)
                        
                        
                        
                table += "</tr>"
                rtable = rtable.lstrip(_format)
                rtable += "\n"
                zongzong = {}
                zongzong['day'] = len(days_l)
                zongzong['pv_all'] = pv_all
                zongzong['UV_all'] = UV_all
                zongzong['VV_all'] = VV_all
                zongzong['NU_all'] = NU_all
                zongzong['VVUV_all'] = VVUV_all
                
                zongzong['SU_all'] = SU_all
                zongzong['FU_all'] = FU_all
                zongzong['NR_all'] = NR_all
                
                zongzong['transcodetime_all'] = transcodetime_all
                zongzong['sd_all'] = sd_all
                zongzong['hd_all'] = hd_all
                zongzong['hd2_all'] = hd2_all
                
                zongzong['c01_all'] = c01_all
                zongzong['c12_all'] = c12_all
                zongzong['c23_all'] = c23_all
                zongzong['c34_all'] = c34_all
                zongzong['c45_all'] = c45_all
                zongzong['c5_all'] = c5_all
               
                
                fv = {}
                
                fv['table'] = table
                fv['rtable'] = rtable
                
                fanhui[xunhuan[vxunhuan]['name']] = fv
                
                
            c.close()
            db.close()
            _url = hashlib.md5(_url)
            _url.digest()
            try:
                mc.set(_url.hexdigest(),fanhui,1024*1024)
            except:
                pass
        else:
            fanhui = m_value
            
        _data = fanhui['All']['rtable']
        #print _data
        self.set_header("Content-Type", "text/csv;charset=UTF-8")
        self.set_header("Content-Disposition", "attachment;filename=Report.csv;charset=UTF-8")
        _data = _data.encode('gb2312','ignore') 
        self.write(_data)
        self.finish()
        
        
class ActiveWeek(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
        
        _stime = self.get_argument('sDate','20120430-20120506').strip()
        _etime = self.get_argument('eDate','20120430-20120506').strip()
        
        
        _stimelist = _stime.split("-")
        _stime = _stimelist[1]
        yy = _stime[0:4]
        mm = _stime[4:6]
        dd = _stime[6:]
        zhou = datetime.date(int(yy),int(mm),int(dd)).isocalendar()[1]
        if len(str(zhou)) == 1:
            zhou = "%s%s" % ("0",zhou)
        _stime = "%s%s" % (yy,zhou)
        print _stime
        
        _etimelist = _etime.split("-")
        _etime = _etimelist[1]
        yy = _etime[0:4]
        mm = _etime[4:6]
        dd = _etime[6:]
        zhou = datetime.date(int(yy),int(mm),int(dd)).isocalendar()[1]
        if len(str(zhou)) == 1:
            zhou = "%s%s" % ("0",zhou)
        _etime = "%s%s" % (yy,zhou) 
        _tt = self.get_argument('tt', '1').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        
        
        

        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        
        _md5 = hashlib.md5(_url)
        _md5.digest()
        m_value = mc.get(_md5.hexdigest()) or {}
        #m_value = {}
        #print m_value
        
        if settings.cache_on == 0:
            m_value = {}
        
        m_value = {}
        
        if not m_value:
            
        
            _items = ['leiji','active_user','huoyuelv']
            

            if _osid == "":
                xunhuan = [{'name':'All','id':'-1'},{'name':'Android','id':'61'},{'name':'iOS','id':'52'},{'name':'WP7','id':'59'}]
            elif _device_type == "":
                xunhuan = [{'name':'All','id':'-1'},{'name':'Phone','id':'1'},{'name':'Pad','id':'2'}]
            else:
                xunhuan = [{'name':'All'}]
            
            db = connectMySQL.connMySQL_stat()
            c=db.cursor()
            fanhui = {}
            fanhui['zongji'] = "0"
            _table = "stat_activeUser_week"
            tihuanriqi = "tihuanriqi"
            for vxunhuan in xrange(len(xunhuan)):
                
                if _osid == "":
                    
                    if _osid == "" and _device_type == "":
                        
                        sql = " SELECT week_period,week_number,sum(active_user) FROM `%s` WHERE week_number >= %s and week_number <= %s  and  app_type = %s and os_id in (%s) and device_type in (-1)  group by week_number order by week_number " % (_table,_stime,_etime,_tt,xunhuan[vxunhuan]['id'])
                        
                        sql_apiresp = " SELECT sum(total_user) FROM `stat_day_user` WHERE date = %s and  app_type = %s and os_id in (%s) and device_type in (-1) " % (tihuanriqi,_tt,xunhuan[vxunhuan]['id'])
                    else:
                        sql = " SELECT week_period,week_number,sum(active_user) FROM `%s` WHERE week_number >= %s and week_number <= %s  and  app_type = %s and os_id in (%s) and device_type in (%s)  group by week_number order by week_number  " % (_table,_stime,_etime,_tt,xunhuan[vxunhuan]['id'],_device_type)
                        
                        sql_apiresp = " SELECT sum(total_user) FROM `stat_day_user` WHERE date = %s and  app_type = %s and os_id in (%s) and device_type in (%s) " % (tihuanriqi,_tt,xunhuan[vxunhuan]['id'],_device_type)
                elif _device_type == "":
                        sql = " SELECT week_period,week_number,sum(active_user) FROM `%s` WHERE week_number >= %s and week_number <= %s  and  app_type = %s and os_id in (%s) and device_type in (%s)  group by week_number order by week_number  " % (_table,_stime,_etime,_tt,_osid,xunhuan[vxunhuan]['id'])
                        
                        sql_apiresp = " SELECT sum(total_user) FROM `stat_day_user` WHERE date = %s and  app_type = %s and os_id in (%s) and device_type in (%s) " % (tihuanriqi,_tt,_osid,xunhuan[vxunhuan]['id'])
                else:
                        sql = " SELECT week_period,week_number,sum(active_user) FROM `%s` WHERE week_number >= %s and week_number <= %s  and  app_type = %s and os_id in (%s) and device_type in (%s)  group by week_number order by week_number  " % (_table,_stime,_etime,_tt,_osid,_device_type)
                        
                        sql_apiresp = " SELECT sum(total_user) FROM `stat_day_user` WHERE date = %s and  app_type = %s and os_id in (%s) and device_type in (%s) " % (tihuanriqi,_tt,_osid,_device_type)
                #print sql
                c.execute(sql)  
                result_all = c.fetchall()
                
                days_l = []
                
                leiji_all = 0
                active_user_all = 0
                huoyuelv_all = 0
                
                leiji_list = []
                active_user_list = []
                huoyuelv_list = []
                
                
                jiriqi = []
                
                for result in result_all:
                    week_period = result[0]
                    houriqilist = week_period.split("-")
                    houriqi = houriqilist[1] 
                    jiriqi.append(str(houriqi))
                
                
                jcjishu = 0
                

                for result in result_all:
                    
                    week_period = result[0]
                    week_number = result[1]
                    active_user = result[2]
                    
                    houriqilist = week_period.split("-")
                    houriqi = houriqilist[1] 
                    
                    if jcjishu == 0:
                        sql_apiresp = sql_apiresp.replace("tihuanriqi",houriqi)
                    else:
                        sql_apiresp = sql_apiresp.replace(jiriqi[jcjishu-1],houriqi)
                    
                    print sql_apiresp
                    c.execute(sql_apiresp)  
                    result_leiji = c.fetchone()
                    
                    if result_leiji[0] == None:
                        leiji = 0
                    else:
                        leiji = result_leiji[0]
                        
                    try:
                        huoyuelv = active_user / leiji
                    except:
                        huoyuelv = 0
                    
                    
                    huoyuelv = round(huoyuelv,4)
                    
                    
                    days_l.append({'week_number':week_number,'week_period':week_period,'active_user':active_user,'leiji':leiji,'huoyuelv':huoyuelv})
                    
                    leiji_all += leiji
                    active_user_all += active_user
                    huoyuelv_all += huoyuelv
                    
                    leiji_list.append(str(leiji))
                    active_user_list.append(str(active_user))
                    huoyuelv_list.append(str(huoyuelv))
                    jcjishu = jcjishu + 1
                
                #print days_l
                #生成表格
                table = ""
                heheshu = 0
                for xy in xrange(len(days_l)):
                    if xy % 2 ==0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                    
                    table += "<tr %s><td>%s</td>" % (bg,cnsort.huoyuezhou(days_l[xy]['week_period']))
                    for items_value in _items:
                        table += cnsort.genTableResultInc4(days_l[xy-1].get(items_value),days_l[xy].get(items_value),items_value,xy)
                    heheshu = days_l[xy].get("leiji")
                    table +="</tr>"
                #生成合计
                table += u"</tbody><tfoot><tr><th class='new_silver_first_n footer'>合计</th>"
                for items_value in _items:
                        if items_value == "huoyuelv":
                            shu = eval("%s%s" % (items_value,'_all'))
                            try:
                                shu = shu / len(days_l)
                            except:
                                shu = 0
                            shu = round(shu,4)
                            nl = str(shu).split(".")
                            if len(str(nl[1])) < 4:
                                table += "<th style=\"text-align:right;\" class=\"footer\">%s0%%</th>" % (shu*100)
                            else:
                                table += "<th style=\"text-align:right;\" class=\"footer\">%s%%</th>" % (shu*100)
                            
                        else:
                            if items_value == "leiji":
                                shu = eval("%s" % heheshu)
                            else:
                                shu = eval("%s%s" % (items_value,'_all'))
                            table += "<th style=\"text-align:right;\" class=\"footer\">%s</th>" % cnsort.num2money(shu)
                
                table += "</tr></tfoot></table></div>"
                
                #生成线性图
                xianx = "["
                
                for xy in xrange(len(days_l)):
                    #yy = days_l[xy]['days'][0:4]
                    #mm = days_l[xy]['days'][4:6]
                    #dd = days_l[xy]['days'][7:]
                    xianx += "'%s'," % (cnsort.huoyuezhou(days_l[xy]['week_period']))
                xianx += "]" 
                
                xiany = {}
                for items_value in _items:
                    shuzu = eval("%s%s" % (items_value,'_list'))
                    shuzu_str = ",".join(shuzu)
                    xiany[items_value] = "[[%s],]" % (shuzu_str)            
                
                
                fv = {}
                
                if len(days_l) > 0:
                    fanhui['zongji'] = "1"
                
                fv['table'] = table
                fv['xianx'] = xianx
                fv['xiany'] = xiany 
                fanhui[xunhuan[vxunhuan]['name']] = fv
                
            
                
            c.close()
            db.close()
            _url = hashlib.md5(_url)
            _url.digest()
            try:
                mc.set(_url.hexdigest(),fanhui,1024*1024)
            except:
                pass
            
        
        else:
            fanhui = m_value
            
        self.write(fanhui)
        self.finish()
        

class ActiveMonth(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
        
        _stime = self.get_argument('sDate','20120401-20120430').strip()
        _etime = self.get_argument('eDate','20120401-20120430').strip()
        
        
        _stimelist = _stime.split("-")
        _stime = _stimelist[1]
        yy = _stime[0:4]
        mm = _stime[4:6]
        dd = _stime[6:]
        _stime = "%s%s" % (yy,mm)
        
        _etimelist = _etime.split("-")
        _etime = _etimelist[1]
        yy = _etime[0:4]
        mm = _etime[4:6]
        dd = _etime[6:]
        _etime = "%s%s" % (yy,mm) 

        
        
        
        _tt = self.get_argument('tt', '1').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        
        
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        m_value = mc.get(_md5.hexdigest()) or {}
        #print m_value
        if settings.cache_on == 0:
            m_value = {}
        m_value = {}
        if not m_value:
        
        
            
            _items = ['leiji','active_user','huoyuelv']
            

            if _osid == "":
                xunhuan = [{'name':'All','id':'-1'},{'name':'Android','id':'61'},{'name':'iOS','id':'52'},{'name':'WP7','id':'59'}]
            elif _device_type == "":
                xunhuan = [{'name':'All','id':'-1'},{'name':'Phone','id':'1'},{'name':'Pad','id':'2'}]
            else:
                xunhuan = [{'name':'All'}]
            
            db = connectMySQL.connMySQL_stat()
            c=db.cursor()
            fanhui = {}
            fanhui['zongji'] = "0"
            _table = "stat_activeUser_month"
            tihuanriqi = "tihuanriqi"
            for vxunhuan in xrange(len(xunhuan)):
                
                if _osid == "":
                    
                    if _osid == "" and _device_type == "":
                        
                        sql = " SELECT month_period,month_number,sum(active_user) FROM `%s` WHERE month_number >= %s and month_number <= %s  and  app_type = %s and os_id in (%s) and device_type in (-1) group by month_number order by month_number " % (_table,_stime,_etime,_tt,xunhuan[vxunhuan]['id'])
                        
                        sql_apiresp = " SELECT sum(total_user) FROM `stat_day_user` WHERE date = %s and  app_type = %s and os_id in (%s) and device_type in (-1) " % (tihuanriqi,_tt,xunhuan[vxunhuan]['id'])
                    else:
                        sql = " SELECT month_period,month_number,sum(active_user) FROM `%s` WHERE month_number >= %s and month_number <= %s  and  app_type = %s and os_id in (%s) and device_type in (%s) group by month_number order by month_number " % (_table,_stime,_etime,_tt,xunhuan[vxunhuan]['id'],_device_type)
                        
                        sql_apiresp = " SELECT sum(total_user) FROM `stat_day_user` WHERE date = %s and  app_type = %s and os_id in (%s) and device_type in (%s) " % (tihuanriqi,_tt,xunhuan[vxunhuan]['id'],_device_type)
                elif _device_type == "":
                        sql = " SELECT month_period,month_number,sum(active_user) FROM `%s` WHERE month_number >= %s and month_number <= %s  and  app_type = %s and os_id in (%s) and device_type in (%s) group by month_number order by month_number " % (_table,_stime,_etime,_tt,_osid,xunhuan[vxunhuan]['id'])
                        
                        sql_apiresp = " SELECT sum(total_user) FROM `stat_day_user` WHERE date = %s and  app_type = %s and os_id in (%s) and device_type in (%s) " % (tihuanriqi,_tt,_osid,xunhuan[vxunhuan]['id'])
                else:
                        sql = " SELECT month_period,month_number,sum(active_user) FROM `%s` WHERE month_number >= %s and month_number <= %s  and  app_type = %s and os_id in (%s) and device_type in (%s) group by month_number order by month_number " % (_table,_stime,_etime,_tt,_osid,_device_type)
                        
                        sql_apiresp = " SELECT sum(total_user) FROM `stat_day_user` WHERE date = %s and  app_type = %s and os_id in (%s) and device_type in (%s) " % (tihuanriqi,_tt,_osid,_device_type)
                #print sql
                c.execute(sql)  
                result_all = c.fetchall()
                
                days_l = []
                
                leiji_all = 0
                active_user_all = 0
                huoyuelv_all = 0
                
                leiji_list = []
                active_user_list = []
                huoyuelv_list = []
                
                jiriqi = []
                
                for result in result_all:
                    month_period = result[0]
                    houriqilist = month_period.split("-")
                    houriqi = houriqilist[1] 
                    jiriqi.append(str(houriqi))
                
                
                jcjishu = 0
                for result in result_all:
                    
                    month_period = result[0]
                    month_number = result[1]
                    active_user = result[2]
                    
                    houriqilist = month_period.split("-")
                    houriqi = houriqilist[1] 
                    
                    
                    if jcjishu == 0:
                        sql_apiresp = sql_apiresp.replace("tihuanriqi",houriqi)
                    else:
                        sql_apiresp = sql_apiresp.replace(jiriqi[jcjishu-1],houriqi)
                    
                    
                    
                    
                    
                    c.execute(sql_apiresp)  
                    result_leiji = c.fetchone()
                    
                    if result_leiji[0] == None:
                        leiji = 0
                    else:
                        leiji = result_leiji[0]
                        
                    try:
                        huoyuelv = active_user / leiji
                    except:
                        huoyuelv = 0
                    
                    
                    huoyuelv = round(huoyuelv,4)
                    
                    
                    days_l.append({'month_number':month_number,'month_period':month_period,'active_user':active_user,'leiji':leiji,'huoyuelv':huoyuelv})
                    
                    leiji_all += leiji
                    active_user_all += active_user
                    huoyuelv_all += huoyuelv
                    
                    leiji_list.append(str(leiji))
                    active_user_list.append(str(active_user))
                    huoyuelv_list.append(str(huoyuelv))
                    jcjishu = jcjishu + 1
                
                #print days_l
                #生成表格
                table = ""
                heheshu = 0
                for xy in xrange(len(days_l)):
                    if xy % 2 ==0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                    
                    table += "<tr %s><td>%s</td>" % (bg,cnsort.huoyueyue(days_l[xy]['month_period']))
                    for items_value in _items:
                        table += cnsort.genTableResultInc4(days_l[xy-1].get(items_value),days_l[xy].get(items_value),items_value,xy)
                    heheshu = days_l[xy].get("leiji")
                    table +="</tr>"
                #生成合计
                table += u"</tbody><tfoot><tr><th class='new_silver_first_n footer'>合计</th>"
                for items_value in _items:
                        if items_value == "huoyuelv":
                            shu = eval("%s%s" % (items_value,'_all'))
                            try:
                                shu = shu / len(days_l)
                            except:
                                shu = 0
                            
                            shu = round(shu,4)
                            nl = str(shu).split(".")
                            if len(str(nl[1])) < 4:
                                table += "<th style=\"text-align:right;\" class=\"footer\">%s0%%</th>" % (shu*100)
                            else:
                                table += "<th style=\"text-align:right;\" class=\"footer\">%s%%</th>" % (shu*100)    
                            
                        else:
                            if items_value == "leiji":
                                shu = eval("%s" % heheshu)
                            else:
                                shu = eval("%s%s" % (items_value,'_all'))
                            table += "<th style=\"text-align:right;\" class=\"footer\">%s</th>" % cnsort.num2money(shu)
                
                table += "</tr></tfoot></table></div>"
                
                #生成线性图
                xianx = "["
                
                for xy in xrange(len(days_l)):
                    #yy = days_l[xy]['days'][0:4]
                    #mm = days_l[xy]['days'][4:6]
                    #dd = days_l[xy]['days'][7:]
                    xianx += "'%s'," % (cnsort.huoyueyue(days_l[xy]['month_period']))
                xianx += "]" 
                
                xiany = {}
                for items_value in _items:
                    shuzu = eval("%s%s" % (items_value,'_list'))
                    shuzu_str = ",".join(shuzu)
                    xiany[items_value] = "[[%s],]" % (shuzu_str)            
                
                
                fv = {}
                
                if len(days_l) > 0:
                    fanhui['zongji'] = "1"
                
                fv['table'] = table
                fv['xianx'] = xianx
                fv['xiany'] = xiany 
                fanhui[xunhuan[vxunhuan]['name']] = fv
                
            
            _url = hashlib.md5(_url)
            _url.digest()
            try:
                mc.set(_url.hexdigest(),fanhui,1024*1024)
            except:
                pass  
            c.close()
            db.close()
        else:
            fanhui = m_value
            
        self.write(fanhui)
        self.finish()





class NewMainPaike_ver(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        _pm = self.get_argument('pm','').strip()
        _items = self.get_argument('items','UV,VV,').strip()
        _vers = self.get_argument('vers','v1.1,v1.2,').strip()
        _items = _items.rstrip(',')
        _items = _items.split(",")
        
        _items_str1 = ""
        for _items_value in _items:
                _items_str1 += "'%s'," % _items_value
        _items_sql = _items_str1.rstrip(",")
        
        print _items_sql 
        _vers = _vers.rstrip(',')
        _vers = _vers.split(",")
        
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        m_value = mc.get(_md5.hexdigest()) or {}
        #print m_value
        
        if settings.cache_on == 0:
            m_value = {}
        
        if not m_value:
        
            
            
            try:
                st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                return
            
            if not _pd:
                ed_time = datetime.datetime.now()
                delta = ed_time - st_time 
                _pd =  abs(delta.days)
            
            _pd = int(_pd)
            et_time = st_time + datetime.timedelta(days=_pd)
            st_datestr = st_time.strftime('%Y%m%d')
            et_datestr = et_time.strftime('%Y%m%d')
            
            all_data = []
            results = {}
            os_data = []
            days = []
            for i in xrange(0,_pd):
                now = datetime.datetime.strptime(st_datestr,'%Y%m%d')
                delta = datetime.timedelta(days=i)  
                n_days = now + delta  
                days.append(n_days.strftime('%Y%m%d'))

            if _pm == "":
                xunhuan = [{'name':'All','id':'1,3,2,8'},{'name':'qudao','id':'2,8'},{'name':'changshang','id':'1'}]
            elif _pm != "":
                xunhuan = [{'name':'All'}]
            
            db = connectMySQL.connMySQL_stat()
            c=db.cursor()
            fanhui = {}
            _table = "stat_day_paike"
            for vxunhuan in xrange(len(xunhuan)):
                
                
                if _pm != "":
                    _pmsql = " and partner_mode in (%s) " % _pm
                else:
                    _pmsql = " "
                tihuanriqi = "tihuanriqi"
                tihuanver = "tihuanver"
                if _pm == "":
                        sql = " SELECT date  FROM `%s` WHERE date >= %s and date < %s and  business_type=4 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (%s)   group by date " % (_table,st_datestr,et_datestr,_osid,_device_type,xunhuan[vxunhuan]['id'])
                        sql_one = " SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(upload),sum(register),sum(total_uploads)  FROM `%s` WHERE date = %s  and  business_type=4 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (%s)    " % (_table,tihuanriqi,_osid,_device_type,xunhuan[vxunhuan]['id'])
                        sql_apiresp = " SELECT pid  FROM `%s` WHERE date = %s  and  business_type=4 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (%s)    " % (_table,tihuanriqi,_osid,_device_type,xunhuan[vxunhuan]['id'])
                        
                elif _pm != "":
                        sql = "SELECT date  FROM `%s` WHERE date >= %s and date < %s and  business_type=4 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (%s)   group by date " % (_table,st_datestr,et_datestr,_osid,_device_type,_pm)
                        sql_one = "SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(upload),sum(register),sum(total_uploads)  FROM `%s` WHERE date = %s and  business_type=4 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (%s)   " % (_table,tihuanriqi,_osid,_device_type,_pm)
                        sql_apiresp = "SELECT pid  FROM `%s` WHERE date = %s and  business_type=4 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (%s)   " % (_table,tihuanriqi,_osid,_device_type,_pm)
                        
                #print sql
                c.execute(sql)  
                result_all = c.fetchall()
                
                UV_list = []
                pv_list = []
                NU_list = []
                VV_list = []
                VVUV_list = []
                SU_list = []
                FU_list = []
                NR_list = []
                hd_list = []
                hd2_list = []
                sd_list = []
                transcodetime_list = []
                
                c01_list = []
                c12_list = []
                c23_list = []
                c34_list = []
                c45_list = []
                c5_list = []
                
                
                days_l = []
                jiriqi = []
                for result in result_all:
                    jiriqi.append(str(result[0]))
                
                #print jiriqi
                #print _vers
                jcjishu = 0
                for result in result_all:
                    _riqis = str(result[0])
                    
                    if jcjishu == 0:
                        sql_one = sql_one.replace("tihuanriqi",_riqis)
                        sql_apiresp = sql_apiresp.replace("tihuanriqi",_riqis)
                    else:
                        sql_one = sql_one.replace(jiriqi[jcjishu-1],_riqis)
                        sql_apiresp = sql_apiresp.replace(jiriqi[jcjishu-1],_riqis)
                    
                    #print _riqi
                    scc = {}
                    qudaocc = {}
                    for vers_value in xrange(len(_vers)):
                        
                        sql_hc = ""
                        sql_qc = ""
                        
                        ver_sql = " and ver = '%s' and prov = 'ALL' and city = 'ALL' " % str(_vers[vers_value])
                        
                        sql_hc = "%s%s" % (sql_one,ver_sql)
                        sql_qc = "%s%s" % (sql_apiresp,ver_sql)

                        c.execute(sql_hc + "  limit 1 ")  
                        result1 = c.fetchone()
                        #print sql_hc + " limit 1 "
                        if result1[0] != None:
                    
                            _riqi = str(result1[0])
                            pv = int(result1[3])
                            UV = int(result1[4])
                            VV = int(result1[5])
                            try:
                                VVUV = VV / UV
                            except:
                                VVUV = 0
                    
                            VVUV = round(VVUV,2)
                            NU = int(result1[6])
                            SU = int(result1[8])
                            NR = int(result1[9])
                            TU = int(result1[10])
                            FU = TU - SU
                            if FU < 0:
                                FU = 0
                            c.execute(sql_apiresp)  
                            pids_list = c.fetchall()
                            pids_str = ""
                            for pids_list_value in pids_list:
                                pids_str += "'%s'," % pids_list_value
                            pids = pids_str.rstrip(",")
                            
                            if pids == "":
                                pids = "'123'"
                    
                    
                            _riqi_start = "%s %s" % (_riqi,"00:00:00")
                            d1 = datetime.datetime.strptime(_riqi_start, '%Y%m%d %H:%M:%S')
                            chuo1 = long(time.mktime(d1.timetuple()))
                    
                            _riqi_end = "%s %s" % (_riqi,"23:59:59")
                            d2 = datetime.datetime.strptime(_riqi_end, '%Y%m%d %H:%M:%S')
                            chuo2 = long(time.mktime(d2.timetuple()))
                    
                            sql = " select sum(transcodetime) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) limit 1" % (chuo1,chuo2,pids) 
                            #print sql
                            c.execute(sql)  
                            res = c.fetchone()
                            
                            if res[0] != None: 
                                zong = res[0]
                            else:
                                zong = 0
                            
                            sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and transcodetime != 0 limit 1 " % (chuo1,chuo2,pids)
                            #print sql
                            c.execute(sql)  
                            res = c.fetchone()
                            geshu = res[0]
 
                            if zong == 0 or geshu == 0:
                                transcodetime = 0 
                            else:
                                transcodetime = zong / geshu
                                
                            transcodetime = round(transcodetime,2)
                            
                            sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and quality = 'sd' limit 1  " % (chuo1,chuo2,pids) 
                            #print sql
                            c.execute(sql)  
                            res = c.fetchone()
                            sd = res[0]
                            
                                
                            sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and quality = 'hd2' limit 1  " % (chuo1,chuo2,pids)
                            #print sql 
                            c.execute(sql)  
                            res = c.fetchone()
                            hd2 = res[0]
                            
                                
                            sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and quality = 'hd' limit 1 " % (chuo1,chuo2,pids) 
                            #print sql
                            c.execute(sql)  
                            res = c.fetchone()
                            hd = res[0]
                            
                                
                            sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and duration > 0 and duration < 60 limit 1 " % (chuo1,chuo2,pids) 
                            #print sql
                            c.execute(sql)  
                            res = c.fetchone()
                            c01 = res[0]
                           
                            
                            sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and duration >= 60 and duration < 120 limit 1 " % (chuo1,chuo2,pids) 
                            #print sql
                            c.execute(sql)  
                            res = c.fetchone()
                            c12 = res[0]
                            
                            
                            sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and duration >= 120 and duration < 180 limit 1 " % (chuo1,chuo2,pids) 
                            #print sql
                            c.execute(sql)  
                            res = c.fetchone()
                            c23 = res[0]
                            
                            
                            sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and duration >= 180 and duration < 240 limit 1 " % (chuo1,chuo2,pids) 
                            #print sql
                            c.execute(sql)  
                            res = c.fetchone()
                            c34 = res[0]
                            
                            
                            sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and duration >= 240 and duration < 300 limit 1 " % (chuo1,chuo2,pids) 
                            #print sql
                            c.execute(sql)  
                            res = c.fetchone()
                            c45 = res[0]
                            
                            
                            sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and duration >= 300 limit 1  " % (chuo1,chuo2,pids) 
                            #print sql
                            c.execute(sql)  
                            res = c.fetchone()
                            c5 = res[0]
                            
                        else:
                            pv = 0
                            UV = 0
                            VV = 0
                            FU = 0
                            VVUV = 0
                            VVUV = round(VVUV,2)
                            NU = 0
                            SU = 0
                            NR = 0
                            transcodetime = 0 
                            transcodetime = round(transcodetime,2)
                            sd = 0
                            hd = 0
                            hd2 = 0
                            c01 = 0
                            c12 = 0
                            c23 = 0
                            c34 = 0
                            c45 = 0
                            c5 = 0
                        
                        sq = {'pv':pv,'UV':UV,'VV':VV,'NU':NU,'VVUV':VVUV,'SU':SU,'NR':NR,'transcodetime':transcodetime,'hd':hd,'sd':sd,'c01':c01,'c12':c12,'c23':c23,'c34':c34,'c45':c45,'c5':c5,'hd2':hd2,'FU':FU}
                        
                        scc[_vers[vers_value]] = sq
                        
                        
                        
                            
                    
                    days_l.append({'days':_riqis,'teams':scc})
                    jcjishu = jcjishu + 1
                    
                #print eval("%s%s" % ('UV','_all'))
                #print days_l
                
                
               
                #生成表格
                
                table = ""
                for xy in xrange(len(days_l)):
                    if xy % 2 ==0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                    table += "<tr %s><td>%s(%s)</td>" % (bg,cnsort.fordate(days_l[xy]['days'],3),common.getxingqi(days_l[xy]['days']))
                    
                    for items_value in _items:
                        table += "<td>"
                        for _vers_value in _vers:
                            table += cnsort.genTableResultInc5(days_l[xy-1]['teams'][_vers_value].get(items_value),days_l[xy]['teams'][_vers_value].get(items_value),items_value,xy,days_l)
                        table += "</td>"
                    table +="</tr>"
                #生成合计
                table += u"</tbody><tfoot><tr><th class='new_silver_first_n footer'>合计</th>"
                for items_value in _items:
                    table += "<th style=\"text-align:right;\" class=\"footer\">"
                    for _vers_value in _vers:
                        
                        if cnsort.checkValueMode(items_value):
                            shu = 0
                            for ccc in xrange(len(days_l)):
                                shu += days_l[ccc]['teams'][_vers_value].get(items_value)
                            
                            if items_value == "CompVV":
                                try:
                                    shu = shu / len(days_l)
                                except:
                                    shu = 0
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    table += "<div class='verdiv'>%s0%%<span style='display:none'>  |  </span></div>" % (shu*100)
                                else:
                                    table += "<div class='verdiv'>%s%%<span style='display:none'>  |  </span></div>" % (shu*100)
                            else:
                                try:
                                    shu = shu / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,2)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 2:
                                    table += "<div class='verdiv'>%s0<span style='display:none'>  |  </span></div>" % shu
                                else:
                                    table += "<div class='verdiv'>%s<span style='display:none'>  |  </span></div>" % shu
                        else:
                            shu = 0
                            for ccc in xrange(len(days_l)):
                                shu += days_l[ccc]['teams'][_vers_value].get(items_value)
                            table += "<div class='verdiv'>%s<span style='display:none'>  |  </span></div>" % cnsort.num2money(shu)
                        
                    table += "</th>"
                table += "</tr></tfoot></table></div>"
                
                
                #生成线性图
                xianx = "["
                
                for xy in xrange(len(days_l)):
                    yy = days_l[xy]['days'][0:4]
                    mm = days_l[xy]['days'][4:6]
                    dd = days_l[xy]['days'][6:]
                    xianx += "'%s/%s/%s'," % (yy,mm,dd)
                xianx += "]" 
                
                fh = {}
                for vers_value in _vers:
                    xiany = "["
                    for items_value in _items:
                        shu = ""
                        for cg in xrange(len(days_l)):
                            shu += "%s," % days_l[cg]['teams'][vers_value][items_value]
                        shu = shu.rstrip(",")
                        qiangzu = []
                        qiangzu.append(items_value)
                        mingzi = cnsort.valueFullNameArr(qiangzu)
                        #xiany += "{name: '%s',data: [%s]}," % (mingzi[0],shu)
                        xiany += "[%s]," % shu
                    xiany += "]"
                    fh[vers_value] = xiany
                

                hehe = {}
                xiany = "["
                for items_value in _items:
                    shu = ""
                    for cg in xrange(len(days_l)):
                        heshu = 0
                        for vers_value in _vers:
                            heshu += days_l[cg]['teams'][vers_value][items_value]
                        shu += "%s," % heshu
                    shu = shu.rstrip(",")
                    qiangzu = []
                    qiangzu.append(items_value)
                    mingzi = cnsort.valueFullNameArr(qiangzu)
                    #xiany += "{name: '%s',data: [%s]}," % (mingzi[0],shu)
                    xiany += "[%s]," % shu
                xiany += "]"
                
                fv = {}
                fv['table'] = table
                fv['xianx'] = xianx
                fv['xian'] = fh
                fv['xian']['he'] = xiany
                
                zongzong = {}
                zongzong['day'] = len(days_l)
                
                fv['zongzong'] = zongzong
                
                fanhui[xunhuan[vxunhuan]['name']] = fv        
                
                
             
            #生成饼图
            _blist = ['UV','VV','NU','SU','NR','hd','sd','c01','c12','c23','c34','c45','c5','hd2','FU']
            qqc = [{'name':'渠道推广','id':'2,8'},{'name':'厂商内置','id':'1'}]
            fc = {}
            for xc in _blist:
                de = "["
                for v in xrange(len(_vers)):
                    for ch in xrange(len(qqc)):

                        if xc == "UV" or xc == "VV" or xc == "NU" or xc == "SU" or xc == "NR":
                            
                            if xc == "UV":
                                kname = "uv"
                            elif xc == "VV":
                                kname = "vv"
                            elif xc == "NU":
                                kname = "newuser"
                            elif xc == "SU":
                                kname = "upload"
                            elif xc == "NR":
                                kname = "register"
                            
                            sql_bingtu = " select sum(%s) from stat_day_paike where ver = '%s' and partner_mode  in (%s) and date >= %s and date < %s and  business_type=4 and pid_stat=1 and os_id in (%s) and device_type in (%s)  " % (kname,_vers[v],qqc[ch]['id'],st_datestr,et_datestr,_osid,_device_type)
                            c.execute(sql_bingtu)  
                            result2 = c.fetchone()
                            if result2[0] != None:
                                zhi = result2[0]
                            else:
                                zhi = 0
                            cname = "%s%s" % (qqc[ch]['name'],_vers[v])
                            de += "['%s',%s]," % (cname,zhi)
                        
                        else:
                            c.execute(" select pid from stat_day_paike where ver = '%s' and partner_mode  in (%s) and date >= %s and date < %s and  business_type=4 and pid_stat=1 and os_id in (%s) and device_type in (%s) " % (_vers[v],qqc[ch]['id'],st_datestr,et_datestr,_osid,_device_type) )  
                            pids_list = c.fetchall()
                            pids_str = ""
                            for pids_list_value in pids_list:
                                pids_str += "'%s'," % pids_list_value
                            pids = pids_str.rstrip(",")
                            d1 = datetime.datetime.strptime(st_datestr, '%Y%m%d')
                            chuos = long(time.mktime(d1.timetuple()))
                            d2 = datetime.datetime.strptime(et_datestr, '%Y%m%d')
                            chuoe = long(time.mktime(d2.timetuple()))
                            
                            if xc == 'hd':
                                try:
                                    c.execute(" select count(id) from paike_upload_vid where date >= %s and date < %s and pid in (%s) and quality = 'hd'  " % (chuos,chuoe,pids) )  
                                    res = c.fetchone()
                                    hd = res[0]
                                except:
                                    hd = 0
                                cname = "%s%s" % (qqc[ch]['name'],_vers[v])
                                de += "['%s',%s]," % (cname,hd)
                                
                            if xc == 'FU':
                                try:
                                    c.execute(" select sum(total_uploads),sum(upload) from stat_day_paike where ver = '%s' and partner_mode  in (%s) and date >= %s and date < %s and  business_type=4 and pid_stat=1 and os_id in (%s) and device_type in (%s)  " % (kname,_vers[v],qqc[ch]['id'],st_datestr,et_datestr,_osid,_device_type) )  
                                    res = c.fetchone()
                                    tu = res[0]
                                    su = res[1]
                                except:
                                    tu = 0
                                    su = 0
                                fu = tu - su
                                cname = "%s%s" % (qqc[ch]['name'],_vers[v])
                                de += "['%s',%s]," % (cname,fu)
                                
                            if xc == 'hd2':
                                try:
                                    c.execute(" select count(id) from paike_upload_vid where date >= %s and date < %s and pid in (%s) and quality = 'hd2'  " % (chuos,chuoe,pids) )  
                                    res = c.fetchone()
                                    hd = res[0]
                                except:
                                    hd = 0
                                cname = "%s%s" % (qqc[ch]['name'],_vers[v])
                                de += "['%s',%s]," % (cname,hd)
                            
                            if xc == 'sd':
                                try:
                                    c.execute(" select count(id) from paike_upload_vid where date >= %s and date < %s and pid in (%s) and quality = 'sd'  " % (chuos,chuoe,pids) )  
                                    res = c.fetchone()
                                    hd = res[0]
                                except:
                                    hd = 0
                                cname = "%s%s" % (qqc[ch]['name'],_vers[v])
                                de += "['%s',%s]," % (cname,hd)
                            if xc == 'c01':
                                try:
                                    c.execute(" select count(id) from paike_upload_vid where date >= %s and date < %s and pid in (%s) and duration >= 0 and duration < 60  " % (chuos,chuoe,pids) )  
                                    res = c.fetchone()
                                    hd = res[0]
                                except:
                                    hd = 0
                                cname = "%s%s" % (qqc[ch]['name'],_vers[v])
                                de += "['%s',%s]," % (cname,hd)
                            if xc == 'c12':
                                try:
                                    c.execute(" select count(id) from paike_upload_vid where date >= %s and date < %s and pid in (%s) and duration >= 60 and duration < 120  " % (chuos,chuoe,pids) )  
                                    res = c.fetchone()
                                    hd = res[0]
                                except:
                                    hd = 0
                                cname = "%s%s" % (qqc[ch]['name'],_vers[v])
                                de += "['%s',%s]," % (cname,hd)
                            if xc == 'c23':
                                try:
                                    c.execute(" select count(id) from paike_upload_vid where date >= %s and date < %s and pid in (%s) and duration >= 120 and duration < 180  " % (chuos,chuoe,pids) )  
                                    res = c.fetchone()
                                    hd = res[0]
                                except:
                                    hd = 0
                                cname = "%s%s" % (qqc[ch]['name'],_vers[v])
                                de += "['%s',%s]," % (cname,hd)
                            if xc == 'c34':
                                try:
                                    c.execute(" select count(id) from paike_upload_vid where date >= %s and date < %s and pid in (%s) and duration >= 180 and duration < 240  " % (chuos,chuoe,pids) )  
                                    res = c.fetchone()
                                    hd = res[0]
                                except:
                                    hd = 0
                                cname = "%s%s" % (qqc[ch]['name'],_vers[v])
                                de += "['%s',%s]," % (cname,hd)
                            if xc == 'c45':
                                try:
                                    c.execute(" select count(id) from paike_upload_vid where date >= %s and date < %s and pid in (%s) and duration >= 240 and duration < 300  " % (chuos,chuoe,pids) )  
                                    res = c.fetchone()
                                    hd = res[0]
                                except:
                                    hd = 0
                                cname = "%s%s" % (qqc[ch]['name'],_vers[v])
                                de += "['%s',%s]," % (cname,hd)
                            if xc == 'c5':
                                try:
                                    c.execute(" select count(id) from paike_upload_vid where date >= %s and date < %s and pid in (%s) and duration >= 300  " % (chuos,chuoe,pids) )  
                                    res = c.fetchone()
                                    hd = res[0]
                                except:
                                    hd = 0
                                cname = "%s%s" % (qqc[ch]['name'],_vers[v])
                                de += "['%s',%s]," % (cname,hd)
                                
                        
                         
                de += "]"
                fc[xc] = de       
            
            fanhui['All']['bingtu'] = fc

            
            c.close()
            db.close()
            _url = hashlib.md5(_url)
            _url.digest()
            try:
                mc.set(_url.hexdigest(),fanhui,1024*1024)
            except:
                pass
        else:
            fanhui = m_value
        self.write(fanhui)
        self.finish()
        
        
class NewMainPaike_ver_new(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        _pm = self.get_argument('pm','').strip()
        _items = self.get_argument('items','UV,VV,').strip()
        _vers = self.get_argument('vers','v1.1,v1.2,').strip()
        _items = _items.rstrip(',')
        _items = _items.split(",")
        
        
        

        
        _items_str1 = ""
        for _items_value in _items:
                _items_str1 += "'%s'," % _items_value
        _items_sql = _items_str1.rstrip(",")
        
        #print _items_sql 
        _vers = _vers.rstrip(',')
        _vers = _vers.split(",")
        
        
        _vers_str1 = ""
        for _vers_value in _vers:
                _vers_str1 += "'%s'," % _vers_value
        _vers_sql = _vers_str1.rstrip(",")
        
        #print _vers_sql 
        
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        m_value = mc.get(_md5.hexdigest()) or {}
        #print m_value
        
        if settings.cache_on == 0:
            m_value = {}
        
        if not m_value:
        
            
            
            try:
                st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                return
            
            if not _pd:
                ed_time = datetime.datetime.now()
                delta = ed_time - st_time 
                _pd =  abs(delta.days)
            
            _pd = int(_pd)
            et_time = st_time + datetime.timedelta(days=_pd)
            st_datestr = st_time.strftime('%Y%m%d')
            et_datestr = et_time.strftime('%Y%m%d')
            
            all_data = []
            results = {}
            os_data = []
            days = []
            for i in xrange(0,_pd):
                now = datetime.datetime.strptime(st_datestr,'%Y%m%d')
                delta = datetime.timedelta(days=i)  
                n_days = now + delta  
                days.append(n_days.strftime('%Y%m%d'))

            if _pm == "":
                xunhuan = [{'name':'All','id':'1,3,2,8'},{'name':'qudao','id':'2,8'},{'name':'changshang','id':'1'}]
            elif _pm != "":
                xunhuan = [{'name':'All'}]
            
            db = connectMySQL.connMySQL_stat()
            c=db.cursor()
            fanhui = {}
            _table = "stat_day_paike_collect"
            _table_bt = _table
            for vxunhuan in xrange(len(xunhuan)):
                
                
                if _pm != "":
                    _pmsql = " and partner_mode in (%s) " % _pm
                else:
                    _pmsql = " "
                tihuanriqi = "tihuanriqi"
                tihuanver = "tihuanver"
                if _pm == "":
                        #sql = " SELECT date  FROM `%s` WHERE date >= %s and date < %s and  business_type=4 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (%s)   group by date " % (_table,st_datestr,et_datestr,_osid,_device_type,xunhuan[vxunhuan]['id'])
                        sql_one = " SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(upload),sum(register),sum(total_uploads),ver  FROM `%s` WHERE date >= %s and date < %s  and  business_type=4 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (%s) and prov = 'ALL' and city = 'ALL'  group by date,ver    " % (_table,st_datestr,et_datestr,_osid,_device_type,xunhuan[vxunhuan]['id'])
                        sql_apiresp = " SELECT pid  FROM `%s` WHERE date = %s  and  business_type=4 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (%s)    " % (_table,tihuanriqi,_osid,_device_type,xunhuan[vxunhuan]['id'])
                        
                elif _pm != "":
                        #sql = "SELECT date  FROM `%s` WHERE date >= %s and date < %s and  business_type=4 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (%s)   group by date " % (_table,st_datestr,et_datestr,_osid,_device_type,_pm)
                        sql_one = "SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(upload),sum(register),sum(total_uploads),ver  FROM `%s` WHERE date >= %s and date < %s and  business_type=4 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (%s) and prov = 'ALL' and city = 'ALL' and ver in (%s) group by date,ver   " % (_table,st_datestr,et_datestr,_osid,_device_type,_pm,_vers_sql)
                        sql_apiresp = "SELECT pid  FROM `%s` WHERE date = %s and  business_type=4 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (%s)   " % (_table,tihuanriqi,_osid,_device_type,_pm)
                        
                print sql_one
                c.execute(sql_one)  
                result_all = c.fetchall()
                
                jiriqi = []
                dujiriqi = []
                for result in result_all:
                    riqi_cc = str(result[0])
                    if riqi_cc not in dujiriqi:
                        dujiriqi.append(riqi_cc)
                    jiriqi.append(str(result[0]))
                
                huaiyun = {}
                jcjishu = 0
                for result1 in result_all:
                
                    _riqi = str(result1[0])
                    _ver = str(result1[11])
                    
                    
                    if jcjishu == 0:
                        sql_apiresp = sql_apiresp.replace("tihuanriqi",_riqi)
                    else:
                        sql_apiresp = sql_apiresp.replace(jiriqi[jcjishu-1],_riqi)
                    
                    ver_sql = " and ver = '%s' and prov = 'ALL' and city = 'ALL' " % str(_ver)
                    
                    sql_hq = "%s%s" % (sql_apiresp,ver_sql)
                    
                    
                    pv = int(result1[3])
                    UV = int(result1[4])
                    VV = int(result1[5])
                    try:
                        VVUV = VV / UV
                    except:
                        VVUV = 0
            
                    VVUV = round(VVUV,2)
                    NU = int(result1[6])
                    SU = int(result1[8])
                    NR = int(result1[9])
                    TU = int(result1[10])
                    FU = TU - SU
                    if FU < 0:
                        FU = 0
                    
                    
                    
                        
                    #print sql_hq
                    
                    c.execute(sql_hq)  
                    pids_list = c.fetchall()
                    pids_str = ""
                    for pids_list_value in pids_list:
                        pids_str += "'%s'," % pids_list_value
                    pids = pids_str.rstrip(",")
                    
                    if pids == "":
                        pids = "'123'"
            
                    
                    #print pids
                    
                    _riqi_start = "%s %s" % (_riqi,"00:00:00")
                    d1 = datetime.datetime.strptime(_riqi_start, '%Y%m%d %H:%M:%S')
                    chuo1 = long(time.mktime(d1.timetuple()))
            
                    _riqi_end = "%s %s" % (_riqi,"23:59:59")
                    d2 = datetime.datetime.strptime(_riqi_end, '%Y%m%d %H:%M:%S')
                    chuo2 = long(time.mktime(d2.timetuple()))
            
                    sql = " select sum(transcodetime) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) limit 1" % (chuo1,chuo2,pids) 
                    #print sql
                    c.execute(sql)  
                    res = c.fetchone()
                    
                    if res[0] != None: 
                        zong = res[0]
                    else:
                        zong = 0
                    
                    sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and transcodetime != 0 limit 1 " % (chuo1,chuo2,pids)
                    #print sql
                    c.execute(sql)  
                    res = c.fetchone()
                    geshu = res[0]

                    if zong == 0 or geshu == 0:
                        transcodetime = 0 
                    else:
                        transcodetime = zong / geshu
                        
                    transcodetime = round(transcodetime,2)
                    
                    sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and quality = 'sd' limit 1  " % (chuo1,chuo2,pids) 
                    #print sql
                    c.execute(sql)  
                    res = c.fetchone()
                    sd = res[0]
                    
                        
                    sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and quality = 'hd2' limit 1  " % (chuo1,chuo2,pids)
                    #print sql 
                    c.execute(sql)  
                    res = c.fetchone()
                    hd2 = res[0]
                    
                        
                    sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and quality = 'hd' limit 1 " % (chuo1,chuo2,pids) 
                    #print sql
                    c.execute(sql)  
                    res = c.fetchone()
                    hd = res[0]
                    
                        
                    sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and duration > 0 and duration < 60 limit 1 " % (chuo1,chuo2,pids) 
                    #print sql
                    c.execute(sql)  
                    res = c.fetchone()
                    c01 = res[0]
                   
                    
                    sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and duration >= 60 and duration < 120 limit 1 " % (chuo1,chuo2,pids) 
                    #print sql
                    c.execute(sql)  
                    res = c.fetchone()
                    c12 = res[0]
                    
                    
                    sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and duration >= 120 and duration < 180 limit 1 " % (chuo1,chuo2,pids) 
                    #print sql
                    c.execute(sql)  
                    res = c.fetchone()
                    c23 = res[0]
                    
                    
                    sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and duration >= 180 and duration < 240 limit 1 " % (chuo1,chuo2,pids) 
                    #print sql
                    c.execute(sql)  
                    res = c.fetchone()
                    c34 = res[0]
                    
                    
                    sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and duration >= 240 and duration < 300 limit 1 " % (chuo1,chuo2,pids) 
                    #print sql
                    c.execute(sql)  
                    res = c.fetchone()
                    c45 = res[0]
                    
                    
                    sql = " select count(id) from paike_upload_vid where date >= %s and date <= %s and pid in (%s) and duration >= 300 limit 1  " % (chuo1,chuo2,pids) 
                    #print sql
                    c.execute(sql)  
                    res = c.fetchone()
                    c5 = res[0]
                    
                    wuxi = {'pv':pv,'UV':UV,'VV':VV,'NU':NU,'VVUV':VVUV,'SU':SU,'NR':NR,'transcodetime':transcodetime,'hd':hd,'sd':sd,'c01':c01,'c12':c12,'c23':c23,'c34':c34,'c45':c45,'c5':c5,'hd2':hd2,'FU':FU}
                    
                    #print _ver
                    hekey = "%s%s" % (_riqi,_ver)
                    huaiyun[hekey] = wuxi
                    
                    jcjishu = jcjishu + 1
                
                
                #print huaiyun
                days_l = []
                
                for result in dujiriqi:
                    _riqis = str(result)
                    
                    scc = {}
                    qudaocc = {}
                    for vers_value in xrange(len(_vers)):
                        
                        henei = "%s%s" % (_riqis,_vers[vers_value])
                        try:
                            sq = {'pv':huaiyun[henei]['pv'],'UV':huaiyun[henei]['UV'],'VV':huaiyun[henei]['VV'],'NU':huaiyun[henei]['NU'],'VVUV':huaiyun[henei]['VVUV'],'SU':huaiyun[henei]['SU'],'NR':huaiyun[henei]['NR'],'transcodetime':huaiyun[henei]['transcodetime'],'hd':huaiyun[henei]['hd'],'sd':huaiyun[henei]['sd'],'c01':huaiyun[henei]['c01'],'c12':huaiyun[henei]['c12'],'c23':huaiyun[henei]['c23'],'c34':huaiyun[henei]['c34'],'c45':huaiyun[henei]['c45'],'c5':huaiyun[henei]['c5'],'hd2':huaiyun[henei]['hd2'],'FU':huaiyun[henei]['FU']}
                        except:
                            sq = {'pv':0,'UV':0,'VV':0,'NU':0,'VVUV':0.0,'SU':0,'NR':0,'transcodetime':0.0,'hd':0,'sd':0,'c01':0,'c12':0,'c23':0,'c34':0,'c45':0,'c5':0,'hd2':0,'FU':0}
                        
                        scc[_vers[vers_value]] = sq
            
                    days_l.append({'days':_riqis,'teams':scc})
                
                
                        
                        
                  
                    
                
                
               
                #生成表格
                
                table = ""
                for xy in xrange(len(days_l)):
                    if xy % 2 ==0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                    table += "<tr %s><td>%s(%s)</td>" % (bg,cnsort.fordate(days_l[xy]['days'],3),common.getxingqi(days_l[xy]['days']))
                    
                    for items_value in _items:
                        table += "<td>"
                        for _vers_value in _vers:
                            table += cnsort.genTableResultInc5(days_l[xy-1]['teams'][_vers_value].get(items_value),days_l[xy]['teams'][_vers_value].get(items_value),items_value,xy,days_l,_vers_value)
                        table += "</td>"
                    table +="</tr>"
                #生成合计
                table += u"</tbody><tfoot><tr><th class='new_silver_first_n footer'>合计</th>"
                for items_value in _items:
                    table += "<th style=\"text-align:right;\" class=\"footer\">"
                    for _vers_value in _vers:
                        
                        if cnsort.checkValueMode(items_value):
                            shu = 0
                            for ccc in xrange(len(days_l)):
                                shu += days_l[ccc]['teams'][_vers_value].get(items_value)
                            
                            if items_value == "CompVV":
                                try:
                                    shu = shu / len(days_l)
                                except:
                                    shu = 0
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    table += "<div class='verdiv'>%s0%%<span style='display:none'>  |  </span></div>" % (shu*100)
                                else:
                                    table += "<div class='verdiv'>%s%%<span style='display:none'>  |  </span></div>" % (shu*100)
                            else:
                                try:
                                    shu = shu / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,2)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 2:
                                    table += "<div class='verdiv'>%s0<span style='display:none'>  |  </span></div>" % shu
                                else:
                                    table += "<div class='verdiv'>%s<span style='display:none'>  |  </span></div>" % shu
                        else:
                            shu = 0
                            for ccc in xrange(len(days_l)):
                                shu += days_l[ccc]['teams'][_vers_value].get(items_value)
                            table += "<div class='verdiv'>%s<span style='display:none'>  |  </span></div>" % cnsort.num2money(shu)
                        
                    table += "</th>"
                table += "</tr></tfoot></table></div>"
                
                
                #生成线性图
                xianx = "["
                
                for xy in xrange(len(days_l)):
                    yy = days_l[xy]['days'][0:4]
                    mm = days_l[xy]['days'][4:6]
                    dd = days_l[xy]['days'][6:]
                    xianx += "'%s/%s/%s'," % (yy,mm,dd)
                xianx += "]" 
                
                fh = {}
                for vers_value in _vers:
                    xiany = "["
                    for items_value in _items:
                        shu = ""
                        for cg in xrange(len(days_l)):
                            shu += "%s," % days_l[cg]['teams'][vers_value][items_value]
                        shu = shu.rstrip(",")
                        qiangzu = []
                        qiangzu.append(items_value)
                        mingzi = cnsort.valueFullNameArr(qiangzu)
                        #xiany += "{name: '%s',data: [%s]}," % (mingzi[0],shu)
                        xiany += "[%s]," % shu
                    xiany += "]"
                    fh[vers_value] = xiany
                

                hehe = {}
                xiany = "["
                for items_value in _items:
                    shu = ""
                    for cg in xrange(len(days_l)):
                        heshu = 0
                        for vers_value in _vers:
                            heshu += days_l[cg]['teams'][vers_value][items_value]
                        shu += "%s," % heshu
                    shu = shu.rstrip(",")
                    qiangzu = []
                    qiangzu.append(items_value)
                    mingzi = cnsort.valueFullNameArr(qiangzu)
                    #xiany += "{name: '%s',data: [%s]}," % (mingzi[0],shu)
                    xiany += "[%s]," % shu
                xiany += "]"
                
                fv = {}
                fv['table'] = table
                fv['xianx'] = xianx
                fv['xian'] = fh
                fv['xian']['he'] = xiany
                
                zongzong = {}
                zongzong['day'] = len(days_l)
                
                fv['zongzong'] = zongzong
                
                fanhui[xunhuan[vxunhuan]['name']] = fv        
                
                
             
            #生成饼图
            _blist = ['UV','VV','NU','SU','NR','hd','sd','c01','c12','c23','c34','c45','c5','hd2','FU']
            qqc = [{'name':'渠道推广','id':'2,8'},{'name':'厂商内置','id':'1'}]
            fc = {}
            for xc in _blist:
                de = "["
                for v in xrange(len(_vers)):
                    for ch in xrange(len(qqc)):

                        if xc == "UV" or xc == "VV" or xc == "NU" or xc == "SU" or xc == "NR":
                            
                            if xc == "UV":
                                kname = "uv"
                            elif xc == "VV":
                                kname = "vv"
                            elif xc == "NU":
                                kname = "newuser"
                            elif xc == "SU":
                                kname = "upload"
                            elif xc == "NR":
                                kname = "register"
                            
                            sql_bingtu = " select sum(%s) from `%s` where ver = '%s' and partner_mode  in (%s) and date >= %s and date < %s and  business_type=4 and pid_stat=1 and os_id in (%s) and device_type in (%s)  " % (kname,_table_bt,_vers[v],qqc[ch]['id'],st_datestr,et_datestr,_osid,_device_type)
                            c.execute(sql_bingtu)  
                            result2 = c.fetchone()
                            if result2[0] != None:
                                zhi = result2[0]
                            else:
                                zhi = 0
                            cname = "%s%s" % (qqc[ch]['name'],_vers[v])
                            de += "['%s',%s]," % (cname,zhi)
                        
                        else:
                            c.execute(" select pid from `%s` where ver = '%s' and partner_mode  in (%s) and date >= %s and date < %s and  business_type=4 and pid_stat=1 and os_id in (%s) and device_type in (%s) " % (_table_bt,_vers[v],qqc[ch]['id'],st_datestr,et_datestr,_osid,_device_type) )  
                            pids_list = c.fetchall()
                            pids_str = ""
                            for pids_list_value in pids_list:
                                pids_str += "'%s'," % pids_list_value
                            pids = pids_str.rstrip(",")
                            d1 = datetime.datetime.strptime(st_datestr, '%Y%m%d')
                            chuos = long(time.mktime(d1.timetuple()))
                            d2 = datetime.datetime.strptime(et_datestr, '%Y%m%d')
                            chuoe = long(time.mktime(d2.timetuple()))
                            
                            if xc == 'hd':
                                try:
                                    c.execute(" select count(id) from paike_upload_vid where date >= %s and date < %s and pid in (%s) and quality = 'hd'  " % (chuos,chuoe,pids) )  
                                    res = c.fetchone()
                                    hd = res[0]
                                except:
                                    hd = 0
                                cname = "%s%s" % (qqc[ch]['name'],_vers[v])
                                de += "['%s',%s]," % (cname,hd)
                                
                            if xc == 'FU':
                                try:
                                    c.execute(" select sum(total_uploads),sum(upload) from `%s` where ver = '%s' and partner_mode  in (%s) and date >= %s and date < %s and  business_type=4 and pid_stat=1 and os_id in (%s) and device_type in (%s)  " % (_table_bt,kname,_vers[v],qqc[ch]['id'],st_datestr,et_datestr,_osid,_device_type) )  
                                    res = c.fetchone()
                                    tu = res[0]
                                    su = res[1]
                                except:
                                    tu = 0
                                    su = 0
                                fu = tu - su
                                cname = "%s%s" % (qqc[ch]['name'],_vers[v])
                                de += "['%s',%s]," % (cname,fu)
                                
                            if xc == 'hd2':
                                try:
                                    c.execute(" select count(id) from paike_upload_vid where date >= %s and date < %s and pid in (%s) and quality = 'hd2'  " % (chuos,chuoe,pids) )  
                                    res = c.fetchone()
                                    hd = res[0]
                                except:
                                    hd = 0
                                cname = "%s%s" % (qqc[ch]['name'],_vers[v])
                                de += "['%s',%s]," % (cname,hd)
                            
                            if xc == 'sd':
                                try:
                                    c.execute(" select count(id) from paike_upload_vid where date >= %s and date < %s and pid in (%s) and quality = 'sd'  " % (chuos,chuoe,pids) )  
                                    res = c.fetchone()
                                    hd = res[0]
                                except:
                                    hd = 0
                                cname = "%s%s" % (qqc[ch]['name'],_vers[v])
                                de += "['%s',%s]," % (cname,hd)
                            if xc == 'c01':
                                try:
                                    c.execute(" select count(id) from paike_upload_vid where date >= %s and date < %s and pid in (%s) and duration >= 0 and duration < 60  " % (chuos,chuoe,pids) )  
                                    res = c.fetchone()
                                    hd = res[0]
                                except:
                                    hd = 0
                                cname = "%s%s" % (qqc[ch]['name'],_vers[v])
                                de += "['%s',%s]," % (cname,hd)
                            if xc == 'c12':
                                try:
                                    c.execute(" select count(id) from paike_upload_vid where date >= %s and date < %s and pid in (%s) and duration >= 60 and duration < 120  " % (chuos,chuoe,pids) )  
                                    res = c.fetchone()
                                    hd = res[0]
                                except:
                                    hd = 0
                                cname = "%s%s" % (qqc[ch]['name'],_vers[v])
                                de += "['%s',%s]," % (cname,hd)
                            if xc == 'c23':
                                try:
                                    c.execute(" select count(id) from paike_upload_vid where date >= %s and date < %s and pid in (%s) and duration >= 120 and duration < 180  " % (chuos,chuoe,pids) )  
                                    res = c.fetchone()
                                    hd = res[0]
                                except:
                                    hd = 0
                                cname = "%s%s" % (qqc[ch]['name'],_vers[v])
                                de += "['%s',%s]," % (cname,hd)
                            if xc == 'c34':
                                try:
                                    c.execute(" select count(id) from paike_upload_vid where date >= %s and date < %s and pid in (%s) and duration >= 180 and duration < 240  " % (chuos,chuoe,pids) )  
                                    res = c.fetchone()
                                    hd = res[0]
                                except:
                                    hd = 0
                                cname = "%s%s" % (qqc[ch]['name'],_vers[v])
                                de += "['%s',%s]," % (cname,hd)
                            if xc == 'c45':
                                try:
                                    c.execute(" select count(id) from paike_upload_vid where date >= %s and date < %s and pid in (%s) and duration >= 240 and duration < 300  " % (chuos,chuoe,pids) )  
                                    res = c.fetchone()
                                    hd = res[0]
                                except:
                                    hd = 0
                                cname = "%s%s" % (qqc[ch]['name'],_vers[v])
                                de += "['%s',%s]," % (cname,hd)
                            if xc == 'c5':
                                try:
                                    c.execute(" select count(id) from paike_upload_vid where date >= %s and date < %s and pid in (%s) and duration >= 300  " % (chuos,chuoe,pids) )  
                                    res = c.fetchone()
                                    hd = res[0]
                                except:
                                    hd = 0
                                cname = "%s%s" % (qqc[ch]['name'],_vers[v])
                                de += "['%s',%s]," % (cname,hd)
                                
                        
                         
                de += "]"
                fc[xc] = de       
            
            fanhui['All']['bingtu'] = fc

            
            c.close()
            db.close()
            _url = hashlib.md5(_url)
            _url.digest()
            try:
                mc.set(_url.hexdigest(),fanhui,1024*1024)
            except:
                pass
        else:
            fanhui = m_value
        self.write(fanhui)
        self.finish()





class NewMainVideo_ver(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        _pm = self.get_argument('pm','').strip()
        _items = self.get_argument('items','UV,VV,').strip()
        _vers = self.get_argument('vers','v1.1,v1.2,').strip()
        _items = _items.rstrip(',')
        _items = _items.split(",")
        _vers = _vers.rstrip(',')
        _vers = _vers.split(",")
        
        _vers_str1 = ""
        for _vers_value in _vers:
                _vers_str1 += "'%s'," % _vers_value
        _vers_sql = _vers_str1.rstrip(",")
        
        #print _vers_sql 
        
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        m_value = mc.get(_md5.hexdigest()) or {}
        #print m_value
        
        if settings.cache_on == 0:
            m_value = {}
        
        if not m_value:
        
        
            
            try:
                st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                return
            
            if not _pd:
                ed_time = datetime.datetime.now()
                delta = ed_time - st_time 
                _pd =  abs(delta.days)
            
            _pd = int(_pd)
            et_time = st_time + datetime.timedelta(days=_pd)
            st_datestr = st_time.strftime('%Y%m%d')
            et_datestr = et_time.strftime('%Y%m%d')
            
            all_data = []
            results = {}
            os_data = []
            days = []
            for i in xrange(0,_pd):
                now = datetime.datetime.strptime(st_datestr,'%Y%m%d')
                delta = datetime.timedelta(days=i)  
                n_days = now + delta  
                days.append(n_days.strftime('%Y%m%d'))

            if _pm == "":
                xunhuan = [{'name':'All','id':'1,3,2,8'},{'name':'qudao','id':'2,8'},{'name':'changshang','id':'1'}]
            elif _pm != "":
                xunhuan = [{'name':'All'}]
            
            db = connectMySQL.connMySQL_stat()
            c=db.cursor()
            fanhui = {}
            _table = "stat_day_total"
            for vxunhuan in xrange(len(xunhuan)):
                
                
                if _pm != "":
                    _pmsql = " and partner_mode in (%s) " % _pm
                else:
                    _pmsql = " "
                tihuanriqi = "tihuanriqi"
                tihuanver = "tihuanver"
                if _pm == "":
                        sql = " SELECT date  FROM `%s` WHERE date >= %s and date < %s and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (%s)   group by date " % (_table,st_datestr,et_datestr,_osid,_device_type,xunhuan[vxunhuan]['id'])
                        sql_one = " SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server,sum(play_hd_times),sum(play_hd_duration),sum(play_sd_times),sum(play_sd_duration),sum(play_hd2_times),sum(play_hd2_duration)  FROM `%s` WHERE date = %s  and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (%s)    " % (_table,tihuanriqi,_osid,_device_type,xunhuan[vxunhuan]['id'])
                        sql_apiresp = " SELECT apiresp FROM `%s` WHERE date = %s and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (%s)  " % (_table,tihuanriqi,_osid,_device_type,xunhuan[vxunhuan]['id'])
                elif _pm != "":
                        sql = "SELECT date  FROM `%s` WHERE date >= %s and date < %s and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (%s)   group by date " % (_table,st_datestr,et_datestr,_osid,_device_type,_pm)
                        sql_one = "SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server,sum(play_hd_times),sum(play_hd_duration),sum(play_sd_times),sum(play_sd_duration),sum(play_hd2_times),sum(play_hd2_duration)  FROM `%s` WHERE date = %s and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (%s)   " % (_table,tihuanriqi,_osid,_device_type,_pm)
                        sql_apiresp = "SELECT apiresp FROM `%s` WHERE date = %s and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (%s)  " % (_table,tihuanriqi,_osid,_device_type,_pm)
                #print sql
                c.execute(sql)  
                result_all = c.fetchall()
                
                
                
                
                days_l = []
                jiriqi = []
                for result in result_all:
                    jiriqi.append(str(result[0]))
                
                #print jiriqi
                #print _vers
                jcjishu = 0
                for result in result_all:
                    _riqis = str(result[0])
                    
                    if jcjishu == 0:
                        sql_one = sql_one.replace("tihuanriqi",_riqis)
                        sql_apiresp = sql_apiresp.replace("tihuanriqi",_riqis)
                    else:
                        sql_one = sql_one.replace(jiriqi[jcjishu-1],_riqis)
                        sql_apiresp = sql_apiresp.replace(jiriqi[jcjishu-1],_riqis)
                    
                    #print _riqi
                    scc = {}
                    qudaocc = {}
                    for vers_value in xrange(len(_vers)):
                        
                        sql_hc = ""
                        sql_qc = ""
                        
                        ver_sql = " and ver = '%s' and prov = 'ALL' and city = 'ALL' " % str(_vers[vers_value])
                        
                        sql_hc = "%s%s" % (sql_one,ver_sql)
                        sql_qc = "%s%s" % (sql_apiresp,ver_sql)
                        
                        print sql_hc
                        c.execute(sql_hc + "  limit 1 ")  
                        result1 = c.fetchone()
                        #print sql_hc + " limit 1 "
                        if result1[0] != None:
                    
                            _riqi = str(result1[0])
                            pv = int(result1[3])
                            UV = int(result1[4])
                            VV = int(result1[5])
                            try:
                                VVUV = VV / UV
                            except:
                                VVUV = 0
                            Dur = int(result1[10])
                            Dur = Dur / 60
                            try:
                                DurVV = Dur / VV
                            except:
                                DurVV = 0
                            try:
                                DurUV = Dur / UV
                            except:
                                DurUV = 0
                            DurVV = round(DurVV,2)
                            DurUV = round(DurUV,2)    
                            VVUV = round(VVUV,2)
                            Comp = int(result1[11])
                                
                            NU = int(result1[6])
                            pm = int(result1[7])
                                
                            try:
                                CompVV = Comp / VV
                            except:
                                CompVV = 0
                            CompVV = round(CompVV,4)
                                
                                
                            before_duration = int(result1[8])
                            before_times = int(result1[9])
                                
                            if (before_duration == 0 or before_times == 0):
                                BefDurTime = 0
                            else:
                                BefDurTime = before_duration/before_times/1000
                                
                            BefDurTime = round(BefDurTime,2)
                                
                            play_load_duration = int(result1[12])
                            play_load_times = int(result1[13])
                                
                            if (play_load_duration == 0 or play_load_times == 0):
                                PlayDurTime = 0
                            else:
                                PlayDurTime = play_load_duration/play_load_times/1000
                                
                            PlayDurTime = round(PlayDurTime,2)
                                
                            if (play_load_times == 0 or VV == 0):
                                PlayTimeVV = 0
                            else:
                                PlayTimeVV = play_load_times/VV
                                
                            PlayTimeVV = round(PlayTimeVV,2)
                                
                            if (play_load_duration == 0 or VV == 0):
                                PlayDurVV = 0
                            else:
                                PlayDurVV = play_load_duration/VV/1000
                            
                            
                            
                            play_hd_times = int(result1[20])

                            play_hd_duration = int(result1[21])

                            play_sd_times = int(result1[22])

                            play_sd_duration = int(result1[23])

                            play_hd2_times = int(result1[24])

                            play_hd2_duration = int(result1[25])
                            
                            PlayDurVV = round(PlayDurVV,2)
                            play_hdsd_times = int(result1[14])
                            play_hdsd_duration = int(result1[15])
                                
                            play_hdsd_durationhe = play_sd_duration + play_hdsd_duration
                            play_hdsd_timeshe = play_sd_times + play_hdsd_times
                            
                                
                            if (play_hdsd_durationhe == 0 or play_hdsd_timeshe == 0):
                                HDSDDurTime = 0
                            else:
                                HDSDDurTime = play_hdsd_durationhe/play_hdsd_timeshe/1000
                                
                            HDSDDurTime = round(HDSDDurTime,2)
                                
                            play_sdhd_times = int(result1[16])
                            play_sdhd_duration = int(result1[17])
                            
                            
                            play_sdhd_durationhe = play_sd_duration + play_sdhd_duration
                            play_sdhd_timeshe = play_sd_times + play_sdhd_times
                                
                            if (play_sdhd_durationhe == 0 or play_sdhd_timeshe == 0):
                                SDHDDurTime = 0
                            else:
                                SDHDDurTime = play_sdhd_durationhe/play_sdhd_timeshe/1000
                            
                            SDHDDurTime = round(SDHDDurTime,2)
                                
                                
                            if (play_hd2_duration == 0 or play_hd2_times == 0):
                                HD2DurTime = 0
                            else:
                                HD2DurTime = play_hd2_duration/play_hd2_times/1000
                                
                            HD2DurTime = round(HD2DurTime,2)
                            
                            
                            
                            cha = 0
                            xuyao_ziduan = ['RelateAPIAveRespTime','VdDetailAPIAveRespTime','VdUrlAPIAveRespTime']
    
                            cha = len(set(_items) & set(xuyao_ziduan))
                            #print sql_qc
                            if cha != 0:
                                play_resptime,play_times,draw_resptime,draw_times,getVideoDetail_resptime,getVideoDetail_times = clientcache.getJsondata_new(sql_qc)
                            else:
                                play_resptime = 0
                                play_times = 0
                                draw_resptime = 0
                                draw_times = 0
                                getVideoDetail_resptime = 0
                                getVideoDetail_times = 0
                                
                                
                            if (draw_resptime == 0 or draw_times == 0):
                                RelateAPIAveRespTime = 0
                            else:
                                RelateAPIAveRespTime = draw_resptime/draw_times/1000
                                
                            RelateAPIAveRespTime = round(RelateAPIAveRespTime,2)
                                
                            if (getVideoDetail_resptime == 0 or getVideoDetail_times == 0):
                                VdDetailAPIAveRespTime = 0
                            else:
                                VdDetailAPIAveRespTime = getVideoDetail_resptime/getVideoDetail_times/1000
                                
                            VdDetailAPIAveRespTime = round(VdDetailAPIAveRespTime,2)
                            if (play_resptime == 0 or play_times == 0):
                                VdUrlAPIAveRespTime = 0
                            else:
                                VdUrlAPIAveRespTime = play_resptime/play_times/1000
                                
                            VdUrlAPIAveRespTime = round(VdUrlAPIAveRespTime,2)   
                        else:
                            pv = 0
                            UV = 0
                            VV = 0
                            try:
                                VVUV = VV / UV
                            except:
                                VVUV = 0
                            Dur = 0
                            try:
                                DurVV = Dur / VV
                            except:
                                DurVV = 0
                            try:
                                DurUV = Dur / UV
                            except:
                                DurUV = 0
                            DurVV = round(DurVV,2)
                            DurUV = round(DurUV,2)    
                            VVUV = round(VVUV,2)
                            
                            
                            
                            Comp = 0
                            
                            NU = 0
                            pm = 0
                            
                            try:
                                CompVV = Comp / VV
                            except:
                                CompVV = 0
                            CompVV = round(CompVV,2)
                            
                            before_duration = 0
                            before_times = 0
                            
                            if (before_duration == 0 or before_times == 0):
                                BefDurTime = 0
                            else:
                                BefDurTime = before_duration/before_times/1000
                            
                            BefDurTime = round(BefDurTime,2)
                            
                            play_load_duration = 0
                            play_load_times = 0
                            
                            if (play_load_duration == 0 or play_load_times == 0):
                                PlayDurTime = 0
                            else:
                                PlayDurTime = play_load_duration/play_load_times/1000
                            
                            PlayDurTime = round(PlayDurTime,2)
                            
                            if (play_load_times == 0 or VV == 0):
                                PlayTimeVV = 0
                            else:
                                PlayTimeVV = play_load_times/VV
                            
                            PlayTimeVV = round(PlayTimeVV,2)
                            
                            if (play_load_duration == 0 or VV == 0):
                                PlayDurVV = 0
                            else:
                                PlayDurVV = play_load_duration/VV/1000
                            
                            PlayDurVV = round(PlayDurVV,2)
                            
                            
                            play_hdsd_times = 0
                            play_hdsd_duration = 0
                            
                            if (play_hdsd_duration == 0 or play_hdsd_times == 0):
                                HDSDDurTime = 0
                            else:
                                HDSDDurTime = play_hdsd_duration/play_hdsd_times/1000
                            
                            HDSDDurTime = round(HDSDDurTime,2)
                            
                            HD2DurTime = round(0,2)
                            
                            play_sdhd_times = 0
                            play_sdhd_duration = 0
                            
                            if (play_sdhd_duration == 0 or play_sdhd_times == 0):
                                SDHDDurTime = 0
                            else:
                                SDHDDurTime = play_sdhd_duration/play_sdhd_times/1000
                            
                            SDHDDurTime = round(SDHDDurTime,2)
                            
                            play_resptime,play_times,draw_resptime,draw_times,getVideoDetail_resptime,getVideoDetail_times = clientcache.getJsondata_new(sql_qc)
                                                
                            if (draw_resptime == 0 or draw_times == 0):
                                RelateAPIAveRespTime = 0
                            else:
                                RelateAPIAveRespTime = draw_resptime/draw_times/1000
                            
                            RelateAPIAveRespTime = round(RelateAPIAveRespTime,2)
                            
                            if (getVideoDetail_resptime == 0 or getVideoDetail_times == 0):
                                VdDetailAPIAveRespTime = 0
                            else:
                                VdDetailAPIAveRespTime = getVideoDetail_resptime/getVideoDetail_times/1000
                            
                            VdDetailAPIAveRespTime = round(VdDetailAPIAveRespTime,2)
                            
                            if (play_resptime == 0 or play_times == 0):
                                VdUrlAPIAveRespTime = 0
                            else:
                                VdUrlAPIAveRespTime = play_resptime/play_times/1000
                            
                            VdUrlAPIAveRespTime = round(VdUrlAPIAveRespTime,2)
                        
                        sq = {'pv':pv,'UV':UV,'VV':VV,'NU':NU,'VVUV':VVUV,'Dur':Dur,'DurVV':DurVV,'DurUV':DurUV,'Comp':Comp,'CompVV':CompVV,'BefDurTime':BefDurTime,'PlayDurTime':PlayDurTime,'PlayTimeVV':PlayTimeVV,'HDSDDurTime':HDSDDurTime,'HD2DurTime':HD2DurTime,'SDHDDurTime':SDHDDurTime,'RelateAPIAveRespTime':RelateAPIAveRespTime,'VdDetailAPIAveRespTime':VdDetailAPIAveRespTime,'VdUrlAPIAveRespTime':VdUrlAPIAveRespTime,'PlayDurVV':PlayDurVV}
                        
                        scc[_vers[vers_value]] = sq
                        
                        
                        
                            
                    
                    days_l.append({'days':_riqis,'teams':scc})
                    jcjishu = jcjishu + 1
                    
                #print eval("%s%s" % ('UV','_all'))
                #print days_l
                
                
               
                #生成表格
                
                table = ""
                for xy in xrange(len(days_l)):
                    if xy % 2 ==0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                    table += "<tr %s><td>%s(%s)</td>" % (bg,cnsort.fordate(days_l[xy]['days'],3),common.getxingqi(days_l[xy]['days']))
                    
                    for items_value in _items:
                        #table += "<td><table><tr>"
                        table += "<td>"
                        for _vers_value in _vers:
                            table += cnsort.genTableResultInc5(days_l[xy-1]['teams'][_vers_value].get(items_value),days_l[xy]['teams'][_vers_value].get(items_value),items_value,xy)
                        #table += "</tr></table></td>"
                        table += "</td>"
                    table +="</tr>"
                #生成合计
                table += u"</tbody><tfoot><tr><th class='new_silver_first_n footer'>合计</th>"
                for items_value in _items:
                    #table += "<th><table><tr>"
                    table += "<th style=\"text-align:right;\" class=\"footer\">"
                    for _vers_value in _vers:
                        
                        if cnsort.checkValueMode(items_value):
                            shu = 0
                            for ccc in xrange(len(days_l)):
                                shu += days_l[ccc]['teams'][_vers_value].get(items_value)
                            
                            if items_value == "CompVV":
                                try:
                                    shu = shu / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    table += "<div class='verdiv'>%s0%%<span style='display:none'>  |  </span></div>" % (shu*100)
                                else:
                                    table += "<div class='verdiv'>%s%%<span style='display:none'>  |  </span></div>" % (shu*100)
                            else:
                                try:
                                    shu = shu / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,2)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 2:
                                    table += "<div class='verdiv'>%s0<span style='display:none'>  |  </span></div>" % shu
                                else:
                                    table += "<div class='verdiv'>%s<span style='display:none'>  |  </span></div>" % shu
                        else:
                            shu = 0
                            for ccc in xrange(len(days_l)):
                                shu += days_l[ccc]['teams'][_vers_value].get(items_value)
                            table += "<div class='verdiv'>%s<span style='display:none'>  |  </span></div>" % cnsort.num2money(shu)
                        
                    #table += "</tr></table></th>"
                    table += "</th>"
                table += "</tr></tfoot></table></div>"
                
                
                #生成线性图
                xianx = "["
                
                for xy in xrange(len(days_l)):
                    yy = days_l[xy]['days'][0:4]
                    mm = days_l[xy]['days'][4:6]
                    dd = days_l[xy]['days'][6:]
                    xianx += "'%s/%s/%s'," % (yy,mm,dd)
                xianx += "]" 
                
                fh = {}
                for vers_value in _vers:
                    xiany = "["
                    for items_value in _items:
                        shu = ""
                        for cg in xrange(len(days_l)):
                            shu += "%s," % days_l[cg]['teams'][vers_value][items_value]
                        shu = shu.rstrip(",")
                        qiangzu = []
                        qiangzu.append(items_value)
                        mingzi = cnsort.valueFullNameArr(qiangzu)
                        #xiany += "{name: '%s',data: [%s]}," % (mingzi[0],shu)
                        xiany += "[%s]," % shu
                    xiany += "]"
                    fh[vers_value] = xiany
                

                hehe = {}
                xiany = "["
                for items_value in _items:
                    shu = ""
                    for cg in xrange(len(days_l)):
                        heshu = 0
                        for vers_value in _vers:
                            heshu += days_l[cg]['teams'][vers_value][items_value]
                        shu += "%s," % heshu
                    shu = shu.rstrip(",")
                    qiangzu = []
                    qiangzu.append(items_value)
                    mingzi = cnsort.valueFullNameArr(qiangzu)
                    #xiany += "{name: '%s',data: [%s]}," % (mingzi[0],shu)
                    xiany += "[%s]," % shu
                xiany += "]"
                
                fv = {}
                fv['table'] = table
                fv['xianx'] = xianx
                fv['xian'] = fh
                fv['xian']['he'] = xiany
                
                zongzong = {}
                zongzong['day'] = len(days_l)
                
                fv['zongzong'] = zongzong
                
                fanhui[xunhuan[vxunhuan]['name']] = fv        
                
                
             
            #生成饼图
            _blist = ['UV','VV','NU','Comp','Dur']
            qqc = [{'name':'渠道推广','id':'2,8'},{'name':'厂商内置','id':'1'}]
            fc = {}
            for xc in _blist:
                de = "["
                for v in xrange(len(_vers)):
                    for ch in xrange(len(qqc)):

                        if xc == "UV":
                            kname = "uv"
                        elif xc == "VV":
                            kname = "vv"
                        elif xc == "NU":
                            kname = "newuser"
                        elif xc == "Comp":
                            kname = "complete"
                        elif xc == "Dur":
                            kname = "duration"
                        
                        sql_bingtu = " select sum(%s) from stat_day_total where ver = '%s' and partner_mode  in (%s) and date >= %s and date < %s and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (%s)  " % (kname,_vers[v],qqc[ch]['id'],st_datestr,et_datestr,_osid,_device_type)

                        c.execute(sql_bingtu)  
                        result2 = c.fetchone()
                        if result2[0] != None:
                            zhi = result2[0]
                        else:
                            zhi = 0
                        cname = "%s%s" % (qqc[ch]['name'],_vers[v])
                        de += "['%s',%s]," % (cname,zhi) 
                de += "]"
                fc[xc] = de       
            
            fanhui['All']['bingtu'] = fc

            
            c.close()
            db.close()
            _url = hashlib.md5(_url)
            _url.digest()
            try:
                mc.set(_url.hexdigest(),fanhui,1024*1024)
            except:
                pass
        else:
            fanhui = m_value
        self.write(fanhui)
        self.finish()




class BeforeDurationMain_ver(tornado.web.RequestHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        _tname = self.get_argument('tname','tname').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        _pm = self.get_argument('pm','').strip()
        _items = self.get_argument('items','UV,VV,').strip()
        _vers = self.get_argument('vers','v1.1,v1.2,').strip()
        _items = _items.rstrip(',')
        _items = _items.split(",")
        _vers = _vers.rstrip(',')
        _vers = _vers.split(",")
        
        _vers_str1 = ""
        for _vers_value in _vers:
                _vers_str1 += "'%s'," % _vers_value
        _vers_sql = _vers_str1.rstrip(",")
        
        #print _vers_sql 
        
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        m_value = mc.get(_md5.hexdigest()) or {}
        #print m_value
        
        if settings.cache_on == 0:
            m_value = {}
        m_value = {}
        if not m_value:
        
        
            
            try:
                st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                return
            
            if not _pd:
                ed_time = datetime.datetime.now()
                delta = ed_time - st_time 
                _pd =  abs(delta.days)
            
            _pd = int(_pd)
            et_time = st_time + datetime.timedelta(days=_pd)
            st_datestr = st_time.strftime('%Y%m%d')
            et_datestr = et_time.strftime('%Y%m%d')
            
            all_data = []
            results = {}
            os_data = []
            days = []
            for i in xrange(0,_pd):
                now = datetime.datetime.strptime(st_datestr,'%Y%m%d')
                delta = datetime.timedelta(days=i)  
                n_days = now + delta  
                days.append(n_days.strftime('%Y%m%d'))
            '''
            if _pm == "":
                xunhuan = [{'name':'All','id':'1,3,2,8'},{'name':'qudao','id':'2,8'},{'name':'changshang','id':'1'}]
            elif _pm != "":
                xunhuan = [{'name':'All'}]
            '''
            xunhuan = [{'name':'All'}]
            db = connectMySQL.connMySQL_stat()
            c=db.cursor()
            fanhui = {}
            _table = "stat_day_total_collect"
            for vxunhuan in xrange(len(xunhuan)):
                
                sql_bdur = "  select sum(num),date,time_type,ver from stat_duration_result where duration_type = 1 and date >= %s and date < %s  and  pid_stat=1 and os_id in (%s) and device_type in (%s) and business_type = 2 and partner_mode in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL'   group by date,ver,time_type " % (st_datestr,et_datestr,_osid,_device_type,_pm)
                        
                sql_one = " SELECT date,sum(before_duration),sum(before_times),ver  FROM `%s` WHERE date >= %s and date < %s  and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (%s)  and prov = 'ALL' and city = 'ALL' group by date,ver order by date desc    " % (_table,st_datestr,et_datestr,_osid,_device_type,_pm)
                
                c.execute(sql_one)  
                result_all = c.fetchall()
                
                c.execute(sql_bdur)
                result_bdur = c.fetchall()
              
                
                
                days_l = []
                jiriqi = []
                dujiriqi = []
                for result in result_all:
                    riqi_cc = str(result[0])
                    if riqi_cc not in dujiriqi:
                        dujiriqi.append(riqi_cc)
                    jiriqi.append(str(result[0]))
                
                huaiyun = {}
                jcjishu = 0
                for result1 in result_all:
                    
                    
                    
                    _ver = str(result1[3])
                    
                    _riqi = str(result1[0])
                    
                    
                    
                    b3 = 0
                    b5 = 0
                    b8 = 0
                    b300 = 0
                    b301 = 0
                    
                    p3 = 0
                    p5 = 0
                    p8 = 0
                    p300 = 0
                    p301 = 0
                    
                    for bdurv in result_bdur:
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 3 and _ver == str(bdurv[3]):
                            b3 = int(bdurv[0])
                        
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 5 and _ver == str(bdurv[3]):
                            b5 = int(bdurv[0])
                            
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 8 and _ver == str(bdurv[3]):
                            b8 = int(bdurv[0])
                            
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 300 and _ver == str(bdurv[3]):
                            b300 = int(bdurv[0])
                        
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 301 and _ver == str(bdurv[3]):
                            b301 = int(bdurv[0])
                            
                    
                    before_duration = int(result1[1])
                    before_times = int(result1[2])
                        
                    if (before_duration == 0 or before_times == 0):
                        BefDurTime = 0
                    else:
                        BefDurTime = before_duration/before_times/1000
                        
                    BefDurTime = round(BefDurTime,2)
                    
                    bdurtime = {}
                    
                    bdurtime['pingjun'] = BefDurTime
                    
                    try:
                        zhanbib = int(b3) / int(result[2])
                    except:
                        zhanbib = 0
                    b3 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(b5) / int(result[2])
                    except:
                        zhanbib = 0
                    b5 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(b8) / int(result[2])
                    except:
                        zhanbib = 0
                    b8 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(b300) / int(result[2])
                    except:
                        zhanbib = 0
                    b300 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(b301) / int(result[2])
                    except:
                        zhanbib = 0
                    b301 = round(zhanbib,2)
                    
                    bdurtime['b3'] = b3
                    bdurtime['b5'] = b5
                    bdurtime['b8'] = b8
                    bdurtime['b300'] = b300
                    bdurtime['b301'] = b301
                    bdurtime['zong'] = int(result[2])
                    
                    wuxi = {'BefDurTime':BefDurTime,'bdurtime':bdurtime}
                    hekey = "%s%s" % (_riqi,_ver)
                    huaiyun[hekey] = wuxi
                    
                    jcjishu = jcjishu + 1
                
                #print huaiyun
                for result in dujiriqi:
                    _riqis = str(result)
                    
                    scc = {}
                    qudaocc = {}
                    for vers_value in xrange(len(_vers)):
                        
                        henei = "%s%s" % (_riqis,_vers[vers_value])
                        #print huaiyun[henei]['UV']
                        try:
                            sq = {'BefDurTime':huaiyun[henei]['BefDurTime'],'bdurtime':huaiyun[henei]['bdurtime']}
                        except:
                            bdurtime = {}
                            bdurtime['b3'] = 0.0
                            bdurtime['b5'] = 0.0
                            bdurtime['b8'] = 0.0
                            bdurtime['b300'] = 0.0
                            bdurtime['b301'] = 0.0
                            bdurtime['zong'] = 0.0
                            
                            sq = {'BefDurTime':0.0,'bdurtime':bdurtime}
                        
                        scc[_vers[vers_value]] = sq
            
                    days_l.append({'days':_riqis,'teams':scc})
                    
                #生成表格
                table = ""
                for xy in xrange(len(days_l)):
                    if xy % 2 ==0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                    table += "<tbody><tr %s><td>%s(%s)</td>" % (bg,cnsort.fordate(days_l[xy]['days'],3),common.getxingqi(days_l[xy]['days']))
                    table += "<td style = 'padding:0px;width:auto;'>"
                    
                    #print days_l
                    
                    for _vers_value in _vers:
                        
                        #table += cnsort.genTableResultInc5(days_l[xy-1]['teams'][_vers_value].get(items_value),days_l[xy]['teams'][_vers_value].get(items_value),items_value,xy,days_l,_vers_value)
                        
                        table += "<div style='float:left;border-right:1px solid #D8D7D7;width:auto;'>"
        
                        
                        
                        pingjun = days_l[xy]['teams'][_vers_value].get('BefDurTime')
                        
                        bdurtime = days_l[xy]['teams'][_vers_value].get('bdurtime')
                        
                        
                        
                        nl = str(bdurtime['b3']).split(".")

                        if len(str(nl[1])) < 4:
                            shu = "%s0%s" % (bdurtime['b3'] * 100,"%")
                        else:
                            shu = "%s%s" % (bdurtime['b3'] * 100,"%")
                        b3 = shu
                        
                        
                        nl = str(bdurtime['b5']).split(".")
                        #print nl
                        if len(str(nl[1])) < 4:
                            shu = "%s0%s" % (bdurtime['b5'] * 100,"%")
                        else:
                            shu = "%s%s" % (bdurtime['b5'] * 100,"%")
                        b5 = shu
                        
                        
                        nl = str(bdurtime['b8']).split(".")
                        #print nl
                        if len(str(nl[1])) < 4:
                            shu = "%s0%s" % (bdurtime['b8'] * 100,"%")
                        else:
                            shu = "%s%s" % (bdurtime['b8'] * 100,"%")
                        b8 = shu
                        
                        nl = str(bdurtime['b300']).split(".")
                        #print nl
                        if len(str(nl[1])) < 4:
                            shu = "%s0%s" % (bdurtime['b300'] * 100,"%")
                        else:
                            shu = "%s%s" % (bdurtime['b300'] * 100,"%")
                        b300 = shu
                        
                        nl = str(bdurtime['b301']).split(".")
                        #print nl
                        if len(str(nl[1])) < 4:
                            shu = "%s0%s" % (bdurtime['b301'] * 100,"%")
                        else:
                            shu = "%s%s" % (bdurtime['b301'] * 100,"%")
                        b301 = shu
                        
                        table += "<div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div></div></div>" % (pingjun,b3,b5,b8,b300,b301)
                    
                    table += "</td>"
                    table += "</tr>"

                table += u"</tbody>"
                
                table += u"</table>"
                
                fv = {}
                fv['table'] = table
                
                zongzong = {}
                zongzong['day'] = len(days_l)
                
                fv['zongzong'] = zongzong
                
                fanhui[xunhuan[vxunhuan]['name']] = fv        
    
            c.close()
            db.close()
            _url = hashlib.md5(_url)
            _url.digest()
            try:
                mc.set(_url.hexdigest(),fanhui,1024*1024)
            except:
                pass
        else:
            fanhui = m_value
            
        
        #self.write(fanhui)
        
        table_tou = "<div style='margin:0px;' class=\"csv-box-header\"><strong>明细</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('X123');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('X123');\" >下载</a></span><a href=\"javascript:getCSVData('X123');\"><img src=\"/static/ykAnalytics2/resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>"
        
        
        table_tou += "<div style=\"overflow:auto;width:900px;height:500px;\" class='bgbg'>";
        
        table_tou += "<table class='new_silver_table' id='X123'><thead><tr><th style='cursor: pointer;' class='new_silver_first_n desc_table' id='123th1' onclick=\" tableSorting('123', 1); \" >日期</th><th>%s</th>" % _tname
        
        
        
        table_tou += "</tr>";

        table_tou += "<tr><th class=\"new_silver_first_n footer\"></th>"
    
        table_tou += "<th class='footer' style='padding:0px;'>";
    
        for vvx in _vers:
        
            vertou = vvx.replace("N/A","早期版本").replace("v","").replace("V","")
            table_tou += "<div style='float:left;border-right:1px solid #D8D7D7;width:auto;'><div style='width:auto;border-bottom:1px solid #D8D7D7;padding:3px;'>%s<span style='display:none'>  |  </span></div><div style='width:auto;padding:0px;' >  <div  class='verdivri' style='pading-top:3px;'>平均时长(s)</div> <div class='verdivri'>t <= 3s <br />优秀</div>  <div class='verdivri'> 3< t <= 5s <br />良好</div>  <div class='verdivri'>5 < t <=8s <br />达标</div>  <div class='verdivri'> 8 < t <= 300s <br />超时</div>  <div class='verdivri'> 300s < t <br />异常 </div></div></div>" % vertou
            table_tou += "</div>"
        
        table_tou += "</th>"
        
        table_tou += "</tr>"
        
        
        table_z = "%s%s" % (table_tou,table)
        
        table_z += "</div>"
        
        self.render("show.html",fanhui=table_z)
        self.finish()
        
        
class PlayDurationMain_ver(tornado.web.RequestHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        _tname = self.get_argument('tname','tname').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        _pm = self.get_argument('pm','').strip()
        _items = self.get_argument('items','UV,VV,').strip()
        _vers = self.get_argument('vers','v1.1,v1.2,').strip()
        _items = _items.rstrip(',')
        _items = _items.split(",")
        _vers = _vers.rstrip(',')
        _vers = _vers.split(",")
        
        _vers_str1 = ""
        for _vers_value in _vers:
                _vers_str1 += "'%s'," % _vers_value
        _vers_sql = _vers_str1.rstrip(",")
        
        #print _vers_sql 
        
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        m_value = mc.get(_md5.hexdigest()) or {}
        #print m_value
        
        if settings.cache_on == 0:
            m_value = {}
        m_value = {}
        if not m_value:
        
        
            
            try:
                st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                return
            
            if not _pd:
                ed_time = datetime.datetime.now()
                delta = ed_time - st_time 
                _pd =  abs(delta.days)
            
            _pd = int(_pd)
            et_time = st_time + datetime.timedelta(days=_pd)
            st_datestr = st_time.strftime('%Y%m%d')
            et_datestr = et_time.strftime('%Y%m%d')
            
            all_data = []
            results = {}
            os_data = []
            days = []
            for i in xrange(0,_pd):
                now = datetime.datetime.strptime(st_datestr,'%Y%m%d')
                delta = datetime.timedelta(days=i)  
                n_days = now + delta  
                days.append(n_days.strftime('%Y%m%d'))
            '''
            if _pm == "":
                xunhuan = [{'name':'All','id':'1,3,2,8'},{'name':'qudao','id':'2,8'},{'name':'changshang','id':'1'}]
            elif _pm != "":
                xunhuan = [{'name':'All'}]
            '''
            xunhuan = [{'name':'All'}]
            db = connectMySQL.connMySQL_stat()
            c=db.cursor()
            fanhui = {}
            _table = "stat_day_total_collect"
            for vxunhuan in xrange(len(xunhuan)):
                
                sql_bdur = "  select sum(num),date,time_type,ver from stat_duration_result where duration_type = 2 and date >= %s and date < %s  and  pid_stat=1 and os_id in (%s) and device_type in (%s) and business_type = 2 and partner_mode in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL'   group by date,ver,time_type " % (st_datestr,et_datestr,_osid,_device_type,_pm)
                        
                sql_one = " SELECT date,sum(play_load_duration),sum(play_load_times),ver  FROM `%s` WHERE date >= %s and date < %s  and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (%s)  and prov = 'ALL' and city = 'ALL' group by date,ver order by date desc    " % (_table,st_datestr,et_datestr,_osid,_device_type,_pm)
                
                c.execute(sql_one)  
                result_all = c.fetchall()
                
                c.execute(sql_bdur)
                result_bdur = c.fetchall()
              
                
                
                days_l = []
                jiriqi = []
                dujiriqi = []
                for result in result_all:
                    riqi_cc = str(result[0])
                    if riqi_cc not in dujiriqi:
                        dujiriqi.append(riqi_cc)
                    jiriqi.append(str(result[0]))
                
                huaiyun = {}
                jcjishu = 0
                for result1 in result_all:
                    
                    
                    
                    _ver = str(result1[3])
                    
                    _riqi = str(result1[0])
                    
                    
                    
                    b3 = 0
                    b5 = 0
                    b8 = 0
                    b300 = 0
                    b301 = 0
                    
                    p3 = 0
                    p5 = 0
                    p8 = 0
                    p300 = 0
                    p301 = 0
                    
                    for bdurv in result_bdur:
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 3 and _ver == str(bdurv[3]):
                            b3 = int(bdurv[0])
                        
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 5 and _ver == str(bdurv[3]):
                            b5 = int(bdurv[0])
                            
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 8 and _ver == str(bdurv[3]):
                            b8 = int(bdurv[0])
                            
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 300 and _ver == str(bdurv[3]):
                            b300 = int(bdurv[0])
                        
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 301 and _ver == str(bdurv[3]):
                            b301 = int(bdurv[0])
                            
                    
                    before_duration = int(result1[1])
                    before_times = int(result1[2])
                        
                    if (before_duration == 0 or before_times == 0):
                        BefDurTime = 0
                    else:
                        BefDurTime = before_duration/before_times/1000
                        
                    BefDurTime = round(BefDurTime,2)
                    
                    bdurtime = {}
                    
                    bdurtime['pingjun'] = BefDurTime
                    
                    try:
                        zhanbib = int(b3) / int(result[2])
                    except:
                        zhanbib = 0
                    b3 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(b5) / int(result[2])
                    except:
                        zhanbib = 0
                    b5 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(b8) / int(result[2])
                    except:
                        zhanbib = 0
                    b8 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(b300) / int(result[2])
                    except:
                        zhanbib = 0
                    b300 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(b301) / int(result[2])
                    except:
                        zhanbib = 0
                    b301 = round(zhanbib,2)
                    
                    bdurtime['b3'] = b3
                    bdurtime['b5'] = b5
                    bdurtime['b8'] = b8
                    bdurtime['b300'] = b300
                    bdurtime['b301'] = b301
                    bdurtime['zong'] = int(result[2])
                    
                    wuxi = {'BefDurTime':BefDurTime,'bdurtime':bdurtime}
                    hekey = "%s%s" % (_riqi,_ver)
                    huaiyun[hekey] = wuxi
                    
                    jcjishu = jcjishu + 1
                
                #print huaiyun
                for result in dujiriqi:
                    _riqis = str(result)
                    
                    scc = {}
                    qudaocc = {}
                    for vers_value in xrange(len(_vers)):
                        
                        henei = "%s%s" % (_riqis,_vers[vers_value])
                        #print huaiyun[henei]['UV']
                        try:
                            sq = {'BefDurTime':huaiyun[henei]['BefDurTime'],'bdurtime':huaiyun[henei]['bdurtime']}
                        except:
                            bdurtime = {}
                            bdurtime['b3'] = 0.0
                            bdurtime['b5'] = 0.0
                            bdurtime['b8'] = 0.0
                            bdurtime['b300'] = 0.0
                            bdurtime['b301'] = 0.0
                            bdurtime['zong'] = 0.0
                            
                            sq = {'BefDurTime':0.0,'bdurtime':bdurtime}
                        
                        scc[_vers[vers_value]] = sq
            
                    days_l.append({'days':_riqis,'teams':scc})
                    
                #生成表格
                table = ""
                for xy in xrange(len(days_l)):
                    if xy % 2 ==0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                    table += "<tbody><tr %s><td>%s(%s)</td>" % (bg,cnsort.fordate(days_l[xy]['days'],3),common.getxingqi(days_l[xy]['days']))
                    table += "<td style = 'padding:0px;width:auto;'>"
                    
                    #print days_l
                    
                    for _vers_value in _vers:
                        
                        #table += cnsort.genTableResultInc5(days_l[xy-1]['teams'][_vers_value].get(items_value),days_l[xy]['teams'][_vers_value].get(items_value),items_value,xy,days_l,_vers_value)
                        
                        table += "<div style='float:left;border-right:1px solid #D8D7D7;width:auto;'>"
        
                        
                        
                        pingjun = days_l[xy]['teams'][_vers_value].get('BefDurTime')
                        
                        bdurtime = days_l[xy]['teams'][_vers_value].get('bdurtime')
                        
                        
                        
                        nl = str(bdurtime['b3']).split(".")

                        if len(str(nl[1])) < 4:
                            shu = "%s0%s" % (bdurtime['b3'] * 100,"%")
                        else:
                            shu = "%s%s" % (bdurtime['b3'] * 100,"%")
                        b3 = shu
                        
                        
                        nl = str(bdurtime['b5']).split(".")
                        #print nl
                        if len(str(nl[1])) < 4:
                            shu = "%s0%s" % (bdurtime['b5'] * 100,"%")
                        else:
                            shu = "%s%s" % (bdurtime['b5'] * 100,"%")
                        b5 = shu
                        
                        
                        nl = str(bdurtime['b8']).split(".")
                        #print nl
                        if len(str(nl[1])) < 4:
                            shu = "%s0%s" % (bdurtime['b8'] * 100,"%")
                        else:
                            shu = "%s%s" % (bdurtime['b8'] * 100,"%")
                        b8 = shu
                        
                        nl = str(bdurtime['b300']).split(".")
                        #print nl
                        if len(str(nl[1])) < 4:
                            shu = "%s0%s" % (bdurtime['b300'] * 100,"%")
                        else:
                            shu = "%s%s" % (bdurtime['b300'] * 100,"%")
                        b300 = shu
                        
                        nl = str(bdurtime['b301']).split(".")
                        #print nl
                        if len(str(nl[1])) < 4:
                            shu = "%s0%s" % (bdurtime['b301'] * 100,"%")
                        else:
                            shu = "%s%s" % (bdurtime['b301'] * 100,"%")
                        b301 = shu
                        
                        table += "<div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div></div></div>" % (pingjun,b3,b5,b8,b300,b301)
                    
                    table += "</td>"
                    table += "</tr>"

                table += u"</tbody>"
                
                table += u"</table>"
                
                fv = {}
                fv['table'] = table
                
                zongzong = {}
                zongzong['day'] = len(days_l)
                
                fv['zongzong'] = zongzong
                
                fanhui[xunhuan[vxunhuan]['name']] = fv        
    
            c.close()
            db.close()
            _url = hashlib.md5(_url)
            _url.digest()
            try:
                mc.set(_url.hexdigest(),fanhui,1024*1024)
            except:
                pass
        else:
            fanhui = m_value
            
        
        #self.write(fanhui)
        
        table_tou = "<div style='margin:0px;' class=\"csv-box-header\"><strong>明细</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('X123');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('X123');\" >下载</a></span><a href=\"javascript:getCSVData('X123');\"><img src=\"/static/ykAnalytics2/resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>"
        
        
        table_tou += "<div style=\"overflow:auto;width:900px;height:500px;\" class='bgbg'>";
        
        table_tou += "<table class='new_silver_table' id='X123'><thead><tr><th style='cursor: pointer;' class='new_silver_first_n desc_table' id='123th1' onclick=\" tableSorting('123', 1); \" >日期</th><th>%s</th>" % _tname
        
        
        
        table_tou += "</tr>";

        table_tou += "<tr><th class=\"new_silver_first_n footer\"></th>"
    
        table_tou += "<th class='footer' style='padding:0px;'>";
    
        for vvx in _vers:
        
            vertou = vvx.replace("N/A","早期版本").replace("v","").replace("V","")
            table_tou += "<div style='float:left;border-right:1px solid #D8D7D7;width:auto;'><div style='width:auto;border-bottom:1px solid #D8D7D7;padding:3px;'>%s<span style='display:none'>  |  </span></div><div style='width:auto;padding:0px;' >  <div  class='verdivri' style='pading-top:3px;'>平均时长(s)</div> <div class='verdivri'>t <= 3s <br />优秀</div>  <div class='verdivri'> 3< t <= 5s <br />良好</div>  <div class='verdivri'>5 < t <=8s <br />达标</div>  <div class='verdivri'> 8 < t <= 300s <br />超时</div>  <div class='verdivri'> 300s < t <br />异常 </div></div></div>" % vertou
            table_tou += "</div>"
        
        table_tou += "</th>"
        
        table_tou += "</tr>"
        
        
        table_z = "%s%s" % (table_tou,table)
        
        table_z += "</div>"
        
        self.render("show.html",fanhui=table_z)
        self.finish()



        
class NewMainVideo_ver_new(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        _pm = self.get_argument('pm','').strip()
        _items = self.get_argument('items','UV,VV,').strip()
        _vers = self.get_argument('vers','v1.1,v1.2,').strip()
        _items = _items.rstrip(',')
        _items = _items.split(",")
        _vers = _vers.rstrip(',')
        _vers = _vers.split(",")
        
        _vers_str1 = ""
        for _vers_value in _vers:
                _vers_str1 += "'%s'," % _vers_value
        _vers_sql = _vers_str1.rstrip(",")
        
        #print _vers_sql 
        
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        m_value = mc.get(_md5.hexdigest()) or {}
        #print m_value
        
        if settings.cache_on == 0:
            m_value = {}
        
        if not m_value:
        
        
            
            try:
                st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                return
            
            if not _pd:
                ed_time = datetime.datetime.now()
                delta = ed_time - st_time 
                _pd =  abs(delta.days)
            
            _pd = int(_pd)
            et_time = st_time + datetime.timedelta(days=_pd)
            st_datestr = st_time.strftime('%Y%m%d')
            et_datestr = et_time.strftime('%Y%m%d')
            
            all_data = []
            results = {}
            os_data = []
            days = []
            for i in xrange(0,_pd):
                now = datetime.datetime.strptime(st_datestr,'%Y%m%d')
                delta = datetime.timedelta(days=i)  
                n_days = now + delta  
                days.append(n_days.strftime('%Y%m%d'))

            if _pm == "":
                xunhuan = [{'name':'All','id':'1,3,2,8'},{'name':'qudao','id':'2,8'},{'name':'changshang','id':'1'}]
            elif _pm != "":
                xunhuan = [{'name':'All'}]
            
            db = connectMySQL.connMySQL_stat()
            c=db.cursor()
            fanhui = {}
            _table = "stat_day_total_collect"
            for vxunhuan in xrange(len(xunhuan)):
                
                
                if _pm != "":
                    _pmsql = " and partner_mode in (%s) " % _pm
                else:
                    _pmsql = " "
                tihuanriqi = "tihuanriqi"
                tihuanver = "tihuanver"
                if _pm == "":
                        #sql = " SELECT date  FROM `%s` WHERE date >= %s and date < %s and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (%s)   group by date " % (_table,st_datestr,et_datestr,_osid,_device_type,xunhuan[vxunhuan]['id'])
                        
                        
                        
                        sql_bdur = "  select sum(num),date,time_type,ver from stat_duration_result where duration_type = 1 and date >= %s and date < %s  and  pid_stat=1 and os_id in (%s) and device_type in (%s) and business_type = 2 and partner_mode in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL'   group by date,ver,time_type " % (st_datestr,et_datestr,_osid,_device_type,xunhuan[vxunhuan]['id'])
                        
                        
                        sql_pdur = "  select sum(num),date,time_type,ver from stat_duration_result where duration_type = 2 and date >= %s and date < %s  and  pid_stat=1 and os_id in (%s) and device_type in (%s) and business_type = 2 and partner_mode in (%s) and ver = 'ALL' and prov = 'ALL' and city = 'ALL'   group by date,ver,time_type " % (st_datestr,et_datestr,_osid,_device_type,xunhuan[vxunhuan]['id'])
                        
                        
                        sql_one = " SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server,sum(play_hd_times),sum(play_hd_duration),sum(play_sd_times),sum(play_sd_duration),sum(play_hd2_times),sum(play_hd2_duration),ver  FROM `%s` WHERE date >= %s and date < %s  and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (%s)  and prov = 'ALL' and city = 'ALL' group by date,ver    " % (_table,st_datestr,et_datestr,_osid,_device_type,xunhuan[vxunhuan]['id'])
                        sql_apiresp = " SELECT apiresp FROM `%s` WHERE date = %s and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (%s)  " % (_table,tihuanriqi,_osid,_device_type,xunhuan[vxunhuan]['id'])
                elif _pm != "":
                        #sql = "SELECT date  FROM `%s` WHERE date >= %s and date < %s and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (%s)   group by date " % (_table,st_datestr,et_datestr,_osid,_device_type,_pm)
                        sql_one = "SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server,sum(play_hd_times),sum(play_hd_duration),sum(play_sd_times),sum(play_sd_duration),sum(play_hd2_times),sum(play_hd2_duration),ver  FROM `%s` WHERE date >= %s and date < %s and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (%s) and ver in (%s) and prov = 'ALL' and city = 'ALL' group by date,ver   " % (_table,st_datestr,et_datestr,_osid,_device_type,_pm,_vers_sql)
                        sql_apiresp = "SELECT apiresp FROM `%s` WHERE date = %s and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (%s)  " % (_table,tihuanriqi,_osid,_device_type,_pm)
                #print sql_one
                c.execute(sql_one)  
                result_all = c.fetchall()
                
                if "BefDurTime" in _items:
                    c.execute(sql_bdur)
                    result_bdur = c.fetchall()
                else:
                    result_bdur = []
                    
                if "PlayDurTime" in _items:
                    c.execute(sql_pdur)
                    result_pdur = c.fetchall()
                else:
                    result_pdur = []
                
                
                days_l = []
                jiriqi = []
                dujiriqi = []
                for result in result_all:
                    riqi_cc = str(result[0])
                    if riqi_cc not in dujiriqi:
                        dujiriqi.append(riqi_cc)
                    jiriqi.append(str(result[0]))
                
                huaiyun = {}
                jcjishu = 0
                for result1 in result_all:
                    
                    
                    
                    _ver = str(result1[26])
                    
                    _riqi = str(result1[0])
                    
                    
                    
                    b3 = 0
                    b5 = 0
                    b8 = 0
                    b300 = 0
                    b301 = 0
                    
                    p3 = 0
                    p5 = 0
                    p8 = 0
                    p300 = 0
                    p301 = 0
                    
                    for bdurv in result_bdur:
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 3 and _ver == str(bdurv[3]):
                            b3 = int(bdurv[0])
                        
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 5 and _ver == str(bdurv[3]):
                            b5 = int(bdurv[0])
                            
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 8 and _ver == str(bdurv[3]):
                            b8 = int(bdurv[0])
                            
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 300 and _ver == str(bdurv[3]):
                            b300 = int(bdurv[0])
                        
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 301 and _ver == str(bdurv[3]):
                            b301 = int(bdurv[0])
                            
                    for bdurv in result_pdur:
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 3 and _ver == str(bdurv[3]):
                            p3 = int(bdurv[0])
                        
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 5 and _ver == str(bdurv[3]):
                            p5 = int(bdurv[0])
                            
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 8 and _ver == str(bdurv[3]):
                            p8 = int(bdurv[0])
                            
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 300 and _ver == str(bdurv[3]):
                            p300 = int(bdurv[0])
                        
                        if _riqi == str(bdurv[1]) and int(bdurv[2]) == 301 and _ver == str(bdurv[3]):
                            p301 = int(bdurv[0])
                    
                    
                    
                    
                    
                    
                    """
                    csql = "  and ver = '%s' and prov = 'ALL' and city = 'ALL'" % _ver
                    
                    sql_apiresp += csql 
                    if jcjishu == 0:
                        sql_apiresp = sql_apiresp.replace("tihuanriqi",_riqi)
                    else:
                        sql_apiresp = sql_apiresp.replace(jiriqi[jcjishu-1],_riqi)
                    """
                    
                    #print 123,_pmsql
                    
                    sql_apiresp = "SELECT apiresp FROM `%s` WHERE date = %s and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (1,3,2,8) and ver = '%s' and prov = 'ALL' and city = 'ALL'  " % (_table,_riqi,_osid,_device_type,_ver)
                    
                    #print sql_apiresp
                    
                    pv = int(result1[3])
                    UV = int(result1[4])
                    VV = int(result1[5])
                    try:
                        VVUV = VV / UV
                    except:
                        VVUV = 0
                    Dur = int(result1[10])
                    Dur = Dur / 60
                    try:
                        DurVV = Dur / VV
                    except:
                        DurVV = 0
                    try:
                        DurUV = Dur / UV
                    except:
                        DurUV = 0
                    DurVV = round(DurVV,2)
                    DurUV = round(DurUV,2)    
                    VVUV = round(VVUV,2)
                    Comp = int(result1[11])
                        
                    NU = int(result1[6])
                    pm = int(result1[7])
                        
                    try:
                        CompVV = Comp / VV
                    except:
                        CompVV = 0
                    CompVV = round(CompVV,4)
                        
                        
                    before_duration = int(result1[8])
                    before_times = int(result1[9])
                        
                    if (before_duration == 0 or before_times == 0):
                        BefDurTime = 0
                    else:
                        BefDurTime = before_duration/before_times/1000
                        
                    BefDurTime = round(BefDurTime,2)
                        
                    play_load_duration = int(result1[12])
                    play_load_times = int(result1[13])
                        
                    if (play_load_duration == 0 or play_load_times == 0):
                        PlayDurTime = 0
                    else:
                        PlayDurTime = play_load_duration/play_load_times/1000
                        
                    PlayDurTime = round(PlayDurTime,2)
                        
                    if (play_load_times == 0 or VV == 0):
                        PlayTimeVV = 0
                    else:
                        PlayTimeVV = play_load_times/VV
                        
                    PlayTimeVV = round(PlayTimeVV,2)
                        
                    if (play_load_duration == 0 or VV == 0):
                        PlayDurVV = 0
                    else:
                        PlayDurVV = play_load_duration/VV/1000
                    
                    
                    
                    play_hd_times = int(result1[20])

                    play_hd_duration = int(result1[21])

                    play_sd_times = int(result1[22])

                    play_sd_duration = int(result1[23])

                    play_hd2_times = int(result1[24])

                    play_hd2_duration = int(result1[25])
                    
                    PlayDurVV = round(PlayDurVV,2)
                    play_hdsd_times = int(result1[14])
                    play_hdsd_duration = int(result1[15])
                        
                    play_hdsd_durationhe = play_sd_duration + play_hdsd_duration
                    play_hdsd_timeshe = play_sd_times + play_hdsd_times
                    
                        
                    if (play_hdsd_durationhe == 0 or play_hdsd_timeshe == 0):
                        HDSDDurTime = 0
                    else:
                        HDSDDurTime = play_hdsd_durationhe/play_hdsd_timeshe/1000
                        
                    HDSDDurTime = round(HDSDDurTime,2)
                        
                    play_sdhd_times = int(result1[16])
                    play_sdhd_duration = int(result1[17])
                    
                    
                    play_sdhd_durationhe = play_sd_duration + play_sdhd_duration
                    play_sdhd_timeshe = play_sd_times + play_sdhd_times
                        
                    if (play_sdhd_durationhe == 0 or play_sdhd_timeshe == 0):
                        SDHDDurTime = 0
                    else:
                        SDHDDurTime = play_sdhd_durationhe/play_sdhd_timeshe/1000
                    
                    SDHDDurTime = round(SDHDDurTime,2)
                        
                        
                    if (play_hd2_duration == 0 or play_hd2_times == 0):
                        HD2DurTime = 0
                    else:
                        HD2DurTime = play_hd2_duration/play_hd2_times/1000
                        
                    HD2DurTime = round(HD2DurTime,2)
                    
                    
                    
                    cha = 0
                    xuyao_ziduan = ['RelateAPIAveRespTime','VdDetailAPIAveRespTime','VdUrlAPIAveRespTime']

                    cha = len(set(_items) & set(xuyao_ziduan))
                    
                    
                    #print '123',sql_apiresp
                    
                    if cha != 0:
                        play_resptime,play_times,draw_resptime,draw_times,getVideoDetail_resptime,getVideoDetail_times = clientcache.getJsondata_new(sql_apiresp)
                    else:
                        play_resptime = 0
                        play_times = 0
                        draw_resptime = 0
                        draw_times = 0
                        getVideoDetail_resptime = 0
                        getVideoDetail_times = 0
                        
                        
                    if (draw_resptime == 0 or draw_times == 0):
                        RelateAPIAveRespTime = 0
                    else:
                        RelateAPIAveRespTime = draw_resptime/draw_times/1000
                        
                    RelateAPIAveRespTime = round(RelateAPIAveRespTime,2)
                        
                    if (getVideoDetail_resptime == 0 or getVideoDetail_times == 0):
                        VdDetailAPIAveRespTime = 0
                    else:
                        VdDetailAPIAveRespTime = getVideoDetail_resptime/getVideoDetail_times/1000
                        
                    VdDetailAPIAveRespTime = round(VdDetailAPIAveRespTime,2)
                    if (play_resptime == 0 or play_times == 0):
                        VdUrlAPIAveRespTime = 0
                    else:
                        VdUrlAPIAveRespTime = play_resptime/play_times/1000
                        
                    VdUrlAPIAveRespTime = round(VdUrlAPIAveRespTime,2)
                    
                    
                    
                    
                    bdurtime = {}
                    
                    bdurtime['pingjun'] = BefDurTime
                    
                    pdurtime = {}
                    
                    pdurtime['pingjun'] = PlayDurTime
                    
                    
                    
                    try:
                        zhanbib = int(b3) / int(result[9])
                    except:
                        zhanbib = 0
                    b3 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(b5) / int(result[9])
                    except:
                        zhanbib = 0
                    b5 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(b8) / int(result[9])
                    except:
                        zhanbib = 0
                    b8 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(b300) / int(result[9])
                    except:
                        zhanbib = 0
                    b300 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(b301) / int(result[9])
                    except:
                        zhanbib = 0
                    b301 = round(zhanbib,2)
                    
                    
                    
                    try:
                        zhanbib = int(p3) / int(result[13])
                    except:
                        zhanbib = 0
                    p3 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(p5) / int(result[13])
                    except:
                        zhanbib = 0
                    p5 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(p8) / int(result[13])
                    except:
                        zhanbib = 0
                    p8 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(p300) / int(result[13])
                    except:
                        zhanbib = 0
                    p300 = round(zhanbib,2)
                    
                    try:
                        zhanbib = int(p301) / int(result[13])
                    except:
                        zhanbib = 0
                    p301 = round(zhanbib,2)
                    
                    
                    
                    bdurtime['b3'] = b3
                    bdurtime['b5'] = b5
                    bdurtime['b8'] = b8
                    bdurtime['b300'] = b300
                    bdurtime['b301'] = b301
                    bdurtime['zong'] = int(result[9])
                    
                    
                    
                    pdurtime['p3'] = p3
                    pdurtime['p5'] = p5
                    pdurtime['p8'] = p8
                    pdurtime['p300'] = p300
                    pdurtime['p301'] = p301
                    pdurtime['zong'] = int(result[13])
                    
                    
                    
                    #print VdUrlAPIAveRespTime,VdDetailAPIAveRespTime,RelateAPIAveRespTime
                    
                    wuxi = {'pv':pv,'UV':UV,'VV':VV,'NU':NU,'VVUV':VVUV,'Dur':Dur,'DurVV':DurVV,'DurUV':DurUV,'Comp':Comp,'CompVV':CompVV,'BefDurTime':BefDurTime,'PlayDurTime':PlayDurTime,'PlayTimeVV':PlayTimeVV,'HDSDDurTime':HDSDDurTime,'HD2DurTime':HD2DurTime,'SDHDDurTime':SDHDDurTime,'RelateAPIAveRespTime':RelateAPIAveRespTime,'VdDetailAPIAveRespTime':VdDetailAPIAveRespTime,'VdUrlAPIAveRespTime':VdUrlAPIAveRespTime,'PlayDurVV':PlayDurVV,'bdurtime':bdurtime,'pdurtime':pdurtime}
                    
                    hekey = "%s%s" % (_riqi,_ver)
                    huaiyun[hekey] = wuxi
                    
                    jcjishu = jcjishu + 1
                
                #print huaiyun
                for result in dujiriqi:
                    _riqis = str(result)
                    
                    #print _riqi
                    scc = {}
                    qudaocc = {}
                    for vers_value in xrange(len(_vers)):
                        
                        henei = "%s%s" % (_riqis,_vers[vers_value])
                        #print huaiyun[henei]['UV']
                        try:
                            sq = {'pv':huaiyun[henei]['pv'],'UV':huaiyun[henei]['UV'],'VV':huaiyun[henei]['VV'],'NU':huaiyun[henei]['NU'],'VVUV':huaiyun[henei]['VVUV'],'Dur':huaiyun[henei]['Dur'],'DurVV':huaiyun[henei]['DurVV'],'DurUV':huaiyun[henei]['DurUV'],'Comp':huaiyun[henei]['Comp'],'CompVV':huaiyun[henei]['CompVV'],'BefDurTime':huaiyun[henei]['BefDurTime'],'PlayDurTime':huaiyun[henei]['PlayDurTime'],'PlayTimeVV':huaiyun[henei]['PlayTimeVV'],'HDSDDurTime':huaiyun[henei]['HDSDDurTime'],'HD2DurTime':huaiyun[henei]['HD2DurTime'],'SDHDDurTime':huaiyun[henei]['SDHDDurTime'],'RelateAPIAveRespTime':huaiyun[henei]['RelateAPIAveRespTime'],'VdDetailAPIAveRespTime':huaiyun[henei]['VdDetailAPIAveRespTime'],'VdUrlAPIAveRespTime':huaiyun[henei]['VdUrlAPIAveRespTime'],'PlayDurVV':huaiyun[henei]['PlayDurVV'],'bdurtime':huaiyun[henei]['bdurtime'],'pdurtime':huaiyun[henei]['pdurtime']}
                        except:
                            bdurtime = {}
                            bdurtime['b3'] = 0.0
                            bdurtime['b5'] = 0.0
                            bdurtime['b8'] = 0.0
                            bdurtime['b300'] = 0.0
                            bdurtime['b301'] = 0.0
                            bdurtime['zong'] = 0.0
                            
                            
                            pdurtime = {}
                            pdurtime['p3'] = 0.0
                            pdurtime['p5'] = 0.0
                            pdurtime['p8'] = 0.0
                            pdurtime['p300'] = 0.0
                            pdurtime['p301'] = 0.0
                            pdurtime['zong'] = 0.0
                            
                            sq = {'pv':0,'UV':0,'VV':0,'NU':0,'VVUV':0.0,'Dur':0,'DurVV':0.0,'DurUV':0.0,'Comp':0,'CompVV':0.0,'BefDurTime':0.0,'PlayDurTime':0.0,'PlayTimeVV':0.0,'HDSDDurTime':0.0,'HD2DurTime':0.0,'SDHDDurTime':0.0,'RelateAPIAveRespTime':0.0,'VdDetailAPIAveRespTime':0.0,'VdUrlAPIAveRespTime':0.0,'PlayDurVV':0.0,'bdurtime':bdurtime,'pdurtime':pdurtime}
                        
                        scc[_vers[vers_value]] = sq
            
                    days_l.append({'days':_riqis,'teams':scc})
                    
                #print eval("%s%s" % ('UV','_all'))
                #print days_l
                
                
               
                #生成表格
                
                table = ""
                for xy in xrange(len(days_l)):
                    if xy % 2 ==0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                    table += "<tr %s><td>%s(%s)</td>" % (bg,cnsort.fordate(days_l[xy]['days'],3),common.getxingqi(days_l[xy]['days']))
                    
                    for items_value in _items:
                        #table += "<td><table><tr>"
                        if items_value == "BefDurTime" or items_value == "PlayDurTime":
                            table += "<td style = 'padding:0px;'>"
                        else:
                            table += "<td >"
                        for _vers_value in _vers:
                            table += cnsort.genTableResultInc5(days_l[xy-1]['teams'][_vers_value].get(items_value),days_l[xy]['teams'][_vers_value].get(items_value),items_value,xy,days_l,_vers_value)
                        #table += "</tr></table></td>"
                        table += "</td>"
                    table +="</tr>"
                #生成合计
                table += u"</tbody><tfoot><tr><th class='new_silver_first_n footer'>合计</th>"
                for items_value in _items:
                    #table += "<th><table><tr>"
                    
                    if items_value == "BefDurTime" or items_value == "PlayDurTime":
                        table += "<th style=\"text-align:right;padding:0px;\" class=\"footer\" >"
                    else:
                        table += "<th style=\"text-align:right;\" class=\"footer\">"
                        
                        
                    for _vers_value in _vers:
                        
                        if cnsort.checkValueMode(items_value):
                            shu = 0
                            
                            
                            for ccc in xrange(len(days_l)):
                                shu += days_l[ccc]['teams'][_vers_value].get(items_value)
                                
                                
                            if items_value == "CompVV":
                                try:
                                    shu = shu / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    table += "<div class='verdiv'>%s0%%<span style='display:none'>  |  </span></div>" % (shu*100)
                                else:
                                    table += "<div class='verdiv'>%s%%<span style='display:none'>  |  </span></div>" % (shu*100)
                            
                            
                            elif items_value == "BefDurTime123":
                            
                                shux = 0
                                
                                b3 = 0
                                b5 = 0
                                b8 = 0
                                b300 = 0
                                b301 = 0
                                
                                for ccc in xrange(len(days_l)):
                                    shux += days_l[ccc]['teams'][_vers_value].get(items_value)
                                    
                                    b3 += days_l[ccc]['teams'][_vers_value].get("bdurtime").get("b3")
                                    b5 += days_l[ccc]['teams'][_vers_value].get("bdurtime").get("b5")
                                    b8 += days_l[ccc]['teams'][_vers_value].get("bdurtime").get("b8")
                                    b300 += days_l[ccc]['teams'][_vers_value].get("bdurtime").get("b300")
                                    b301 += days_l[ccc]['teams'][_vers_value].get("bdurtime").get("b301")
                                
                                #print shux,'kkk'
                                
                                try:
                                    shu = b3 / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    b3 = "%s0%%" % (shu*100)
                                else:
                                    b3 = "%s%%" % (shu*100)
                                    
                                try:
                                    shu = b5 / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    b5 = "%s0%%" % (shu*100)
                                else:
                                    b5 = "%s%%" % (shu*100)
                                
                                try:
                                    shu = b8 / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    b8 = "%s0%%" % (shu*100)
                                else:
                                    b8 = "%s%%" % (shu*100)
                                
                                try:
                                    shu = b300 / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    b300 = "%s0%%" % (shu*100)
                                else:
                                    b300 = "%s%%" % (shu*100)
                                
                                try:
                                    shu = b301 / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    b301 = "%s0%%" % (shu*100)
                                else:
                                    b301 = "%s%%" % (shu*100)
                                
                                
                                
                                table += "<div style='float:left;display:inline;border-right:1px solid #D8D7D7;'><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div></div>" % (shux,b3,b5,b8,b300,b301)
                            
                            
                            elif items_value == "PlayDurTime123":
                            
                                shux = 0
                                
                                p3 = 0
                                p5 = 0
                                p8 = 0
                                p300 = 0
                                p301 = 0
                                
                                for ccc in xrange(len(days_l)):
                                    shux += days_l[ccc]['teams'][_vers_value].get(items_value)
                                    p3 += days_l[ccc]['teams'][_vers_value].get("pdurtime").get("p3")
                                    p5 += days_l[ccc]['teams'][_vers_value].get("pdurtime").get("p5")
                                    p8 += days_l[ccc]['teams'][_vers_value].get("pdurtime").get("p8")
                                    p300 += days_l[ccc]['teams'][_vers_value].get("pdurtime").get("p300")
                                    p301 += days_l[ccc]['teams'][_vers_value].get("pdurtime").get("p301")
                                
                                
                                try:
                                    shu = p3 / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    p3 = "%s0%%" % (shu*100)
                                else:
                                    p3 = "%s%%" % (shu*100)
                                    
                                try:
                                    shu = p5 / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    p5 = "%s0%%" % (shu*100)
                                else:
                                    p5 = "%s%%" % (shu*100)
                                
                                try:
                                    shu = p8 / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    p8 = "%s0%%" % (shu*100)
                                else:
                                    p8 = "%s%%" % (shu*100)
                                
                                try:
                                    shu = p300 / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    p300 = "%s0%%" % (shu*100)
                                else:
                                    p300 = "%s%%" % (shu*100)
                                
                                try:
                                    shu = p301 / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,4)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 4:
                                    p301 = "%s0%%" % (shu*100)
                                else:
                                    p301 = "%s%%" % (shu*100)
                                
                                
                                
                                table += "<div style='float:left;display:inline;border-right:1px solid #D8D7D7;'><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div></div>" % (shux,p3,p5,p8,p300,p301)
                            
                                
                            else:
                                try:
                                    shu = shu / len(days_l)
                                except:
                                    shu = 0
                                shu = round(shu,2)
                                nl = str(shu).split(".")
                                if len(str(nl[1])) < 2:
                                    table += "<div class='verdiv'>%s0<span style='display:none'>  |  </span></div>" % shu
                                else:
                                    table += "<div class='verdiv'>%s<span style='display:none'>  |  </span></div>" % shu
                        
                        
                        
                        
                        else:
                            shu = 0
                            for ccc in xrange(len(days_l)):
                                shu += days_l[ccc]['teams'][_vers_value].get(items_value)
                            table += "<div class='verdiv'>%s<span style='display:none'>  |  </span></div>" % cnsort.num2money(shu)
                        
                    #table += "</tr></table></th>"
                    table += "</th>"
                table += "</tr></tfoot></table>"
                
                
                #生成线性图
                xianx = "["
                
                for xy in xrange(len(days_l)):
                    yy = days_l[xy]['days'][0:4]
                    mm = days_l[xy]['days'][4:6]
                    dd = days_l[xy]['days'][6:]
                    xianx += "'%s/%s/%s'," % (yy,mm,dd)
                xianx += "]" 
                
                fh = {}
                for vers_value in _vers:
                    xiany = "["
                    for items_value in _items:
                        shu = ""
                        for cg in xrange(len(days_l)):
                            shu += "%s," % days_l[cg]['teams'][vers_value][items_value]
                        shu = shu.rstrip(",")
                        qiangzu = []
                        qiangzu.append(items_value)
                        mingzi = cnsort.valueFullNameArr(qiangzu)
                        #xiany += "{name: '%s',data: [%s]}," % (mingzi[0],shu)
                        xiany += "[%s]," % shu
                    xiany += "]"
                    fh[vers_value] = xiany
                

                hehe = {}
                xiany = "["
                for items_value in _items:
                    shu = ""
                    for cg in xrange(len(days_l)):
                        heshu = 0
                        for vers_value in _vers:
                            heshu += days_l[cg]['teams'][vers_value][items_value]
                        shu += "%s," % heshu
                    shu = shu.rstrip(",")
                    qiangzu = []
                    qiangzu.append(items_value)
                    mingzi = cnsort.valueFullNameArr(qiangzu)
                    #xiany += "{name: '%s',data: [%s]}," % (mingzi[0],shu)
                    xiany += "[%s]," % shu
                xiany += "]"
                
                fv = {}
                fv['table'] = table
                fv['xianx'] = xianx
                fv['xian'] = fh
                fv['xian']['he'] = xiany
                
                zongzong = {}
                zongzong['day'] = len(days_l)
                
                fv['zongzong'] = zongzong
                
                fanhui[xunhuan[vxunhuan]['name']] = fv        
                
                
             
            #生成饼图
            _blist = ['UV','VV','NU','Comp','Dur']
            qqc = [{'name':'渠道推广','id':'2,8'},{'name':'厂商内置','id':'1'}]
            fc = {}
            for xc in _blist:
                de = "["
                for v in xrange(len(_vers)):
                    for ch in xrange(len(qqc)):

                        if xc == "UV":
                            kname = "uv"
                        elif xc == "VV":
                            kname = "vv"
                        elif xc == "NU":
                            kname = "newuser"
                        elif xc == "Comp":
                            kname = "complete"
                        elif xc == "Dur":
                            kname = "duration"
                        
                        sql_bingtu = " select sum(%s) from `%s` where ver = '%s' and partner_mode  in (%s) and date >= %s and date < %s and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (%s)  " % (kname,_table,_vers[v],qqc[ch]['id'],st_datestr,et_datestr,_osid,_device_type)

                        c.execute(sql_bingtu)  
                        result2 = c.fetchone()
                        if result2[0] != None:
                            zhi = result2[0]
                        else:
                            zhi = 0
                        cname = "%s%s" % (qqc[ch]['name'],_vers[v])
                        de += "['%s',%s]," % (cname,zhi) 
                de += "]"
                fc[xc] = de       
            
            fanhui['All']['bingtu'] = fc

            
            c.close()
            db.close()
            _url = hashlib.md5(_url)
            _url.digest()
            try:
                mc.set(_url.hexdigest(),fanhui,1024*1024)
            except:
                pass
        else:
            fanhui = m_value
            
            
        self.write(fanhui)
        self.finish()
        
        
class ReturnVer(BaseHandler):
    def get(self): 
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        _table = self.get_argument('table','total').strip()
        
        
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        m_value = mc.get(_md5.hexdigest()) or {}
        #print m_value
        if settings.cache_on == 0:
            m_value = {}
        
        if not m_value:
        
            try:
                st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                return
            
            if not _pd:
                ed_time = datetime.datetime.now()
                delta = ed_time - st_time 
                _pd =  abs(delta.days)
            
            _pd = int(_pd)
            et_time = st_time + datetime.timedelta(days=_pd)
            st_datestr = st_time.strftime('%Y%m%d')
            et_datestr = et_time.strftime('%Y%m%d')
            
            
            db = connectMySQL.connMySQL_stat()
            c=db.cursor()
            fanhui={}
            
            if _table == "total":
                fack = []
                table = "<div> <fieldset><legend>版本统计项<input type=\"checkbox\" onclick=\"checkAll(this, 'NewMainVideoCheckbox3')\" ></legend>"
                _table += "%s" % "_collect"
                sql = " select distinct(ver) from `stat_day_%s` where os_id in (%s) and device_type in (%s) and partner_mode in (1,3,2,8) and ver != 'ALL' and ver != '' and ver != 'N/A' and business_type = 2 and   pid_stat = 1 and ver != '2.#' and ver != '2.' and ver != 'x12.4' and ver != '2.r/1'  order by ver asc " % (_table,_osid,_device_type)
                #print sql
                c.execute(sql)
                resjson = c.fetchall()
                if resjson:
                    for x in resjson:
                        #table += "<div style=\"float:left\" class=\"ckbText\"><input type=\"checkbox\" name=\"NewMainVideoCheckbox3\" id=\"NewMainVideo%s\" value=\"%s\">%s</div>" % (x[0],x[0],str(x[0]).replace("N/A",u"早期版本").lstrip("v").lstrip("V"))
                        v_name = str(x[0]).lstrip("v").lstrip("V")
                        guolv = eval("common.videover%s_%s" % (_osid,_device_type))
                        #print v_name
                        if v_name not in guolv and str(v_name).find(".") != -1:
                            fack.append([str(x[0]).lstrip("v").lstrip("V"),x[0]])
                    fack = sorted(fack,reverse=True)
                    fack.append(['N/A','N/A'])
                    #print fack
                    for i in xrange(len(fack)):
                        table += "<div style=\"float:left\" class=\"ckbText\"><input type=\"checkbox\" name=\"NewMainVideoCheckbox3\" id=\"NewMainVideo%s\" value=\"%s\">%s</div>" % (fack[i][1],fack[i][1],str(fack[i][0]).replace("N/A",u"早期版本"))
                    
                else:
                    table += "<div style=\"float:left\" class=\"ckbText\">没有版本</div>"
                table += "</fieldset></div>"
            else:
                _table += "%s" % "_collect"
                table = "<div class=\"statsTableHeader\"> <span class=\"selHeader\">版本统计项<input type=\"checkbox\" onclick=\"checkAll(this, 'NewMainPaikeCheckbox3')\" ></span><div class=\"selbox\">"
                fack = []
                sql = " select distinct(ver) from `stat_day_%s` where os_id in (%s) and device_type in (%s) and partner_mode in (1,3,2,8) and ver != 'ALL' and ver != 'N/A'  and business_type = 4 and   pid_stat = 1 and ver != '2.#' and ver != '2.' order by ver asc " % (_table,_osid,_device_type)
                #print sql
                c.execute(sql)
                resjson = c.fetchall()
                if resjson:
                    for x in resjson:
                        #table += "<div style=\"float:left\" class=\"ckbText\"><input type=\"checkbox\" name=\"NewMainPaikeCheckbox3\" id=\"NewMainPaike%s\" value=\"%s\">%s</div>" % (x[0],x[0],str(x[0]).replace("N/A",u"早期版本").lstrip("v").lstrip("V"))
                        v_name = str(x[0]).lstrip("v").lstrip("V")
                        guolv = eval("common.paikever%s_%s" % (_osid,_device_type))
                        if v_name not in guolv and str(v_name).find(".") != -1:
                            fack.append([str(x[0]).lstrip("v").lstrip("V"),x[0]])
                    fack = sorted(fack,reverse=True)
                    fack.append(['N/A','N/A'])
                    for i in xrange(len(fack)):
                        table += "<div style=\"float:left\" class=\"ckbText\"><input type=\"checkbox\" name=\"NewMainPaikeCheckbox3\" id=\"NewMainPaike%s\" value=\"%s\">%s</div>" % (fack[i][1],fack[i][1],str(fack[i][0]).replace("N/A",u"早期版本"))
                    
                else:
                    table += "<div style=\"float:left\" class=\"ckbText\">没有版本</div>"
                table += "</div><div class=\"clear\"></div></div>"
            
            fanhui['table'] = table
            
            _url = hashlib.md5(_url)
            _url.digest()
            try:
                mc.set(_url.hexdigest(),fanhui,1024*1024)
            except:
                pass
            
            c.close()
            db.close()
        else:
            fanhui = m_value
        self.write(fanhui)
        self.finish()




class NewBoardVideo(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        _url = self.request.uri
        
        try:
            st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
        except :
            self.send_error(400, desc='invalid argument')
            return
        
        if not _pd:
            ed_time = datetime.datetime.now()
            delta = ed_time - st_time 
            _pd =  abs(delta.days)
        
        _pd = int(_pd)
        et_time = st_time + datetime.timedelta(days=_pd)
        st_datestr = st_time.strftime('%Y%m%d')
        et_datestr = et_time.strftime('%Y%m%d')
        
        all_data = []
        results = {}
        os_data = []
        
        days = []
        
        for i in xrange(0,_pd):
            now = datetime.datetime.strptime(st_datestr,'%Y%m%d')
            delta = datetime.timedelta(days=i)  
            n_days = now + delta  
            days.append(n_days.strftime('%Y%m%d'))
        
        
        #print days
        
        xunhuan = [{'name':'Phone','id':'1'},{'name':'Pad','id':'2'}]
        db = connectMySQL.connMySQL_stat()
        c=db.cursor()
        
        fanhui = {}
        
        
        for vxunhuan in xrange(len(xunhuan)):
            
            days = sorted(days,reverse=True)
            
            st_datestr = datetime.datetime.now().strftime('%Y%m%d')
            #st_datestr = "20121104"
            
            if xunhuan[vxunhuan]['id'] == "1":
                pindaosql2 = "%s" % "5"
                pindaosql1 = "%s" % "1"
                appxunhuan = common.Video_Phone_app
            elif xunhuan[vxunhuan]['id'] == "2":
                pindaosql2 = "%s" % "2"
                pindaosql1 = "%s" % "3"
                appxunhuan = common.Video_Pad_app
                
                
            #排行表3开始
            table3 = u"<thead><tr><th>应用软件</th>"
            
            for timez in days:
                table3 += "<th>%s</th>" % cnsort.fordate(timez,3)
            
            table3 += "</tr></thead><tbody>"
            jishu = 0
            xianys = []
            minglist = ""
            
            for appxunhuani in xrange(len(appxunhuan)):
                
                
                
                minglist += "'%s'," % appxunhuan[appxunhuani]['name']
                
                if jishu % 2 == 0:
                    cclass = "new_silver_odd"
                else:
                    cclass = "new_silver_even"
                
                linshi = []
                sql = " SELECT app_rank,date,app_id FROM `stat_store_board` where device_id = '%s' and app_id = '%s' and board_type = '%s'  group by date order by date desc  " % (xunhuan[vxunhuan]['id'],appxunhuan[appxunhuani]['id'],pindaosql1)
                #print sql
                c.execute(sql)  
                res_app = c.fetchall()
                for res_appa in res_app:
                    linshi.append({'date':str(res_appa[1]),'rand':str(res_appa[0])})
                    
                table3 += "<tr class='%s'  ><td style='text-align:left;padding-left:30px;'>%s%s%s%s</td> " % (cclass,"<img width=20 height=20 src='http://10.103.13.15:8000/static/img/",appxunhuan[appxunhuani]['img'],"'/>&nbsp;",appxunhuan[appxunhuani]['name'])
                
                #print appxunhuan[appxunhuani]['name']
                #print linshi
                days = sorted(days,reverse=True)
                for timec in days:
                    nadao = ""
                    for linshix in linshi:
                        if str(timec) == str(linshix['date']):
                            nadao = linshix['rand']
                    if nadao == "":
                        nadao = ">200"
                    #print timec,nadao
                    table3 += "<td>%s</td>" % nadao
                     
                jishu = jishu + 1
                
                
                days = sorted(days)
                #print linshi
                xianyz = ""
                for timec in days:
                    nadaoc = ""
                    for linshix in linshi:
                        if str(timec) == str(linshix['date']):
                            nadaoc = linshix['rand']
                    if nadaoc == "":
                        nadaoc = 200
                    xianyz += "%s," % nadaoc 
                xianyz = xianyz.rstrip(",")
                xianys.append(xianyz)
                
                table3 += "</tr></tbody>"
            #线性图开始
            xianx = "["
            for xy in xrange(len(days)):
                yy = days[xy][0:4]
                mm = days[xy][4:6]
                dd = days[xy][6:]
                xianx += "'%s/%s/%s'," % (yy,mm,dd)
            xianx = xianx.rstrip(",")
            xianx += "]"
            
            xiany = "["
            
            #print xianys
            for xyc in xianys:
                xiany += "[%s]," % xyc
            xiany = xiany.rstrip(",")
            xiany += "]"
            
            xianm = "["
            
            minglist = minglist.rstrip(",")
            
            xianm += minglist
            
            xianm += "]"
            
             
 
            
            #排行表1开始
            sql = " SELECT app_rank,app_name,board_type,device_id,app_logo,app_id FROM `stat_store_board` where device_id = '%s' and board_type = '%s' and date = '%s' order by app_rank asc limit 200  " % (xunhuan[vxunhuan]['id'],pindaosql1,st_datestr)
            #print sql
            c.execute(sql)  
            res= c.fetchall()
            youku = ""
            table1 = ""
            jishu = 0
            for x in res:
                app_rank = x[0]
                app_name = x[1]
                board_type = x[2]
                app_logo = x[4]
                app_id = str(x[5])
                
                bgc=''
                name_c=''
                app_name = app_name.strip()
                if app_id == '492031078' or app_id == '336141475' or app_id == '394075284':
                    bgc = "background:#FFFF00;"
                    name_c = " id = 'youkude' "
                    youku = "<tr class='new_silver_even' ><td style='text-align:center;background:#FFFF00;'>%s</td><td class=\"\" style=\"text-align:left;padding-left:50px;background:#FFFF00;\"><img width=50 height=50 src='http://10.103.13.15:8000/static/img/%s'/>&nbsp;%s</td></tr>" % (app_rank,app_logo,app_name)
                
                if jishu % 2 == 0:
                    table1+="<tr  class='new_silver_even'><td class=\"new_silver_first_n\" style='text-align:center;%s'>%s</td><td class=\"\" style=\"text-align:left;padding-left:50px;%s\"><img width=20 height=20 src='http://10.103.13.15:8000/static/img/%s'/>&nbsp;%s<div %s></div></td></tr>" % (bgc,app_rank,bgc,app_logo,app_name,name_c)
                else:
                    table1+="<tr  class='new_silver_odd'><td class=\"new_silver_first_n\" style='text-align:center;%s'>%s</td><td class=\"\" style=\"text-align:left;padding-left:50px;%s\"><img width=20 height=20 src='http://10.103.13.15:8000/static/img/%s'/>&nbsp;%s<div %s></div></td></tr>" % (bgc,app_rank,bgc,app_logo,app_name,name_c)
                jishu = jishu + 1
                
                
            #排行表2开始
            sql = " SELECT app_rank,app_name,board_type,device_id,app_logo,app_id FROM `stat_store_board` where device_id = '%s' and board_type = '%s' and date = '%s' order by app_rank asc limit 200  " % (xunhuan[vxunhuan]['id'],pindaosql2,st_datestr)
            #print sql
            c.execute(sql)  
            res= c.fetchall()
            youku = ""
            table2 = ""
            jishu = 0
            for x in res:
                app_rank = x[0]
                app_name = x[1]
                board_type = x[2]
                app_logo = x[4]
                app_id = str(x[5])
                
                bgc=''
                name_c=''
                app_name = app_name.strip()
                if app_id == '492031078' or app_id == '336141475' or app_id == '394075284':
                    bgc = "background:#FFFF00;"
                    name_c = " id = 'youkude' "
                    youku = "<tr class='new_silver_even' ><td style='text-align:center;background:#FFFF00;'>%s</td><td class=\"\" style=\"text-align:left;padding-left:50px;background:#FFFF00;\"><img width=50 height=50 src='http://10.103.13.15:8000/static/img/%s'/>&nbsp;%s</td></tr>" % (app_rank,app_logo,app_name)
                
                if jishu % 2 == 0:
                    table2+="<tr  class='new_silver_even'><td class=\"new_silver_first_n\" style='text-align:center;%s'>%s</td><td class=\"\" style=\"text-align:left;padding-left:50px;%s\"><img width=20 height=20 src='http://10.103.13.15:8000/static/img/%s'/>&nbsp;%s<div %s></div></td></tr>" % (bgc,app_rank,bgc,app_logo,app_name,name_c)
                else:
                    table2+="<tr  class='new_silver_odd'><td class=\"new_silver_first_n\" style='text-align:center;%s'>%s</td><td class=\"\" style=\"text-align:left;padding-left:50px;%s\"><img width=20 height=20 src='http://10.103.13.15:8000/static/img/%s'/>&nbsp;%s<div %s></div></td></tr>" % (bgc,app_rank,bgc,app_logo,app_name,name_c)
                jishu = jishu + 1
            
            
            
            fv = {}
            
            fv['table1'] = table1
            fv['table2'] = table2
            fv['table3'] = table3
            fv['xianx'] = xianx
            fv['xiany'] = xiany
            fv['xianm'] = xianm
            
            fanhui[xunhuan[vxunhuan]['name']] = fv
        
        c.close()
        db.close()
            
        self.write(fanhui)
        self.finish()
        
        

class NewBoardPaike(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        _url = self.request.uri
        
        try:
            st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
        except :
            self.send_error(400, desc='invalid argument')
            return
        
        if not _pd:
            ed_time = datetime.datetime.now()
            delta = ed_time - st_time 
            _pd =  abs(delta.days)
        
        _pd = int(_pd)
        et_time = st_time + datetime.timedelta(days=_pd)
        st_datestr = st_time.strftime('%Y%m%d')
        et_datestr = et_time.strftime('%Y%m%d')
        
        all_data = []
        results = {}
        os_data = []
        
        days = []
        
        for i in xrange(0,_pd):
            now = datetime.datetime.strptime(st_datestr,'%Y%m%d')
            delta = datetime.timedelta(days=i)  
            n_days = now + delta  
            days.append(n_days.strftime('%Y%m%d'))
        
        days = sorted(days,reverse=True)
        
        
        
        
        xunhuan = [{'name':'Phone','id':'1'}]
        db = connectMySQL.connMySQL_stat()
        c=db.cursor()
        
        fanhui = {}
        
        
        for vxunhuan in xrange(len(xunhuan)):
            
            st_datestr = datetime.datetime.now().strftime('%Y%m%d')
            #st_datestr = "20121104"
            
            if xunhuan[vxunhuan]['id'] == "1":
                pindaosql2 = "%s" % "5"
                pindaosql1 = "%s" % "4"
                appxunhuan = common.Paike_Phone_app
                
                
            #排行表3开始
            table3 = u"<thead><tr><th>应用软件</th>"
            
            for timez in days:
                table3 += "<th>%s</th>" % cnsort.fordate(timez,3)
            
            table3 += "</tr></thead><tbody>"
            jishu = 0
            xianys = []
            minglist = ""
            for appxunhuani in xrange(len(appxunhuan)):
                
                minglist += "'%s'," % appxunhuan[appxunhuani]['name']
                
                if jishu % 2 == 0:
                    cclass = "new_silver_odd"
                else:
                    cclass = "new_silver_even"
                
                linshi = []
                sql = " SELECT app_rank,date FROM `stat_store_board` where device_id = '%s' and app_id = '%s' and board_type = '%s' group by date order by app_rank asc  " % (xunhuan[vxunhuan]['id'],appxunhuan[appxunhuani]['id'],pindaosql1)
                c.execute(sql)  
                res_app = c.fetchall()
                for res_appa in res_app:
                    linshi.append({'rand':str(res_appa[0]),'date':str(res_appa[1])})
                    
                table3 += "<tr class='%s'  ><td style='text-align:left;padding-left:30px;'>%s%s%s%s</td> " % (cclass,"<img width=20 height=20 src='http://10.103.13.15:8000/static/img/",appxunhuan[appxunhuani]['img'],"'/>&nbsp;",appxunhuan[appxunhuani]['name'])
                
                
                #print linshi
                days = sorted(days,reverse=True)
                for timec in days:
                    nadao = ""
                    for linshix in linshi:
                        if str(timec) == str(linshix['date']):
                            nadao = linshix['rand']
                            nadaoc = linshix['rand']
                    if nadao == "":
                        nadao = u">200"
                        nadaoc = 200
                        
                    table3 += "<td>%s</td>" % nadao
                jishu = jishu + 1
                
                days = sorted(days)
                xianyz = ""
                for timec in days:
                    nadao = ""
                    for linshix in linshi:
                        if str(timec) == str(linshix['date']):
                            nadao = linshix['rand']
                            nadaoc = linshix['rand']
                    if nadao == "":
                        nadao = u">200"
                        nadaoc = 200
                        
                    xianyz += "%s," % nadaoc 
                xianyz = xianyz.rstrip(",")
                xianys.append(xianyz)
                
                table3 += "</tr></tbody>"
            #线性图开始
            xianx = "["
            #days = sorted(days)
            #print days
            for xy in xrange(len(days)):
                yy = days[xy][0:4]
                mm = days[xy][4:6]
                dd = days[xy][6:]
                xianx += "'%s/%s/%s'," % (yy,mm,dd)
            xianx = xianx.rstrip(",")
            xianx += "]"
            
            xiany = "["
                
            for xyc in xianys:
                xiany += "[%s]," % xyc
            xiany = xiany.rstrip(",")
            xiany += "]"
            
            xianm = "["
            
            minglist = minglist.rstrip(",")
            
            xianm += minglist
            
            xianm += "]"
            
             
 
            
            #排行表1开始
            sql = " SELECT app_rank,app_name,board_type,device_id,app_logo,app_id FROM `stat_store_board` where device_id = '%s' and board_type = '%s' and date = '%s' order by app_rank asc limit 200  " % (xunhuan[vxunhuan]['id'],pindaosql1,st_datestr)
            #print sql
            c.execute(sql)  
            res= c.fetchall()
            youku = ""
            table1 = ""
            jishu = 0
            for x in res:
                app_rank = x[0]
                app_name = x[1]
                board_type = x[2]
                app_logo = x[4]
                app_id = str(x[5])
                
                bgc=''
                name_c=''
                app_name = app_name.strip()
                if app_id == '492031078' or app_id == '336141475' or app_id == '394075284':
                    bgc = "background:#FFFF00;"
                    name_c = " id = 'youkude' "
                    youku = "<tr class='new_silver_even' ><td style='text-align:center;background:#FFFF00;'>%s</td><td class=\"\" style=\"text-align:left;padding-left:50px;background:#FFFF00;\"><img width=50 height=50 src='http://10.103.13.15:8000/static/img/%s'/>&nbsp;%s</td></tr>" % (app_rank,app_logo,app_name)
                
                if jishu % 2 == 0:
                    table1+="<tr  class='new_silver_even'><td class=\"new_silver_first_n\" style='text-align:center;%s'>%s</td><td class=\"\" style=\"text-align:left;padding-left:50px;%s\"><img width=20 height=20 src='http://10.103.13.15:8000/static/img/%s'/>&nbsp;%s<div %s></div></td></tr>" % (bgc,app_rank,bgc,app_logo,app_name,name_c)
                else:
                    table1+="<tr  class='new_silver_odd'><td class=\"new_silver_first_n\" style='text-align:center;%s'>%s</td><td class=\"\" style=\"text-align:left;padding-left:50px;%s\"><img width=20 height=20 src='http://10.103.13.15:8000/static/img/%s'/>&nbsp;%s<div %s></div></td></tr>" % (bgc,app_rank,bgc,app_logo,app_name,name_c)
                jishu = jishu + 1
                
                
            #排行表2开始
            sql = " SELECT app_rank,app_name,board_type,device_id,app_logo,app_id FROM `stat_store_board` where device_id = '%s' and board_type = '%s' and date = '%s' order by app_rank asc limit 200  " % (xunhuan[vxunhuan]['id'],pindaosql2,st_datestr)
            #print sql
            c.execute(sql)  
            res= c.fetchall()
            youku = ""
            table2 = ""
            jishu = 0
            for x in res:
                app_rank = x[0]
                app_name = x[1]
                board_type = x[2]
                app_logo = x[4]
                app_id = str(x[5])
                
                bgc=''
                name_c=''
                app_name = app_name.strip()
                if app_id == '492031078' or app_id == '336141475' or app_id == '394075284':
                    bgc = "background:#FFFF00;"
                    name_c = " id = 'youkude' "
                    youku = "<tr class='new_silver_even' ><td style='text-align:center;background:#FFFF00;'>%s</td><td class=\"\" style=\"text-align:left;padding-left:50px;background:#FFFF00;\"><img width=50 height=50 src='http://10.103.13.15:8000/static/img/%s'/>&nbsp;%s</td></tr>" % (app_rank,app_logo,app_name)
                
                if jishu % 2 == 0:
                    table2+="<tr  class='new_silver_even'><td class=\"new_silver_first_n\" style='text-align:center;%s'>%s</td><td class=\"\" style=\"text-align:left;padding-left:50px;%s\"><img width=20 height=20 src='http://10.103.13.15:8000/static/img/%s'/>&nbsp;%s<div %s></div></td></tr>" % (bgc,app_rank,bgc,app_logo,app_name,name_c)
                else:
                    table2+="<tr  class='new_silver_odd'><td class=\"new_silver_first_n\" style='text-align:center;%s'>%s</td><td class=\"\" style=\"text-align:left;padding-left:50px;%s\"><img width=20 height=20 src='http://10.103.13.15:8000/static/img/%s'/>&nbsp;%s<div %s></div></td></tr>" % (bgc,app_rank,bgc,app_logo,app_name,name_c)
                jishu = jishu + 1
            
            
            
            fv = {}
            
            fv['table1'] = table1
            fv['table2'] = table2
            fv['table3'] = table3
            fv['xianx'] = xianx
            fv['xiany'] = xiany
            fv['xianm'] = xianm
            
            fanhui[xunhuan[vxunhuan]['name']] = fv
        
        c.close()
        db.close()
            
        self.write(fanhui)
        self.finish()
        
        

class OutSite(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        _pid = self.get_argument('pid','2bd988a9275d4a61').strip()
        _device_type = self.get_argument('dt','').strip()
        _url = self.request.uri
        _items = ['VV']
        
        try:
            st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
        except :
            self.send_error(400, desc='invalid argument')
            return
        
        if not _pd:
            ed_time = datetime.datetime.now()
            delta = ed_time - st_time 
            _pd =  abs(delta.days)
        
        _pd = int(_pd)
        et_time = st_time + datetime.timedelta(days=_pd)
        st_datestr = st_time.strftime('%Y%m%d')
        et_datestr = et_time.strftime('%Y%m%d')
        
        
        xunhuan = [{'name':'All','id':'1'}]
        db = connectMySQL.connMySQL_stat()
        c=db.cursor()
        
        fanhui = {}
        
        
        for vxunhuan in xrange(len(xunhuan)):
            
            
            
            sql = " select sum(vv),date from stat_day_partner where pid_stat = 1 and date >= %s and date < %s and pid in ('%s') and partner_mode in (9) and ver = 'ALL' and prov = 'ALL' and city = 'ALL' group by date " % (st_datestr,et_datestr,_pid)
            print sql
            VV_all = 0
            VV_list = []
            
            days_l = []
            
            c.execute(sql)  
            result_all = c.fetchall()
            
            
            for result in result_all:
                
                _riqi = str(result[1])
                VV = int(result[0])
                days_l.append({'days':_riqi,'VV':VV})
                VV_all += VV
                VV_list.append(str(VV))
            
            
            #生成线性图
            xianx = "["
            
            for xy in xrange(len(days_l)):
                yy = days_l[xy]['days'][0:4]
                mm = days_l[xy]['days'][4:6]
                dd = days_l[xy]['days'][6:]
                xianx += "'%s/%s/%s'," % (yy,mm,dd)
            xianx = xianx.rstrip(",")
            xianx += "]" 
            
            xiany = "["
            for items_value in _items:
                shuzu = eval("%s%s" % (items_value,'_list'))
                shuzu_str = ",".join(shuzu)
                qiangzu = []
                qiangzu.append(items_value)
                xiany += "[%s]," % (shuzu_str)            
            xiany = xiany.rstrip(",")
            xiany += "]"                


            #生成表格
            table = ""
            for xy in xrange(len(days_l)):
                if xy % 2 ==0:
                    bg = " class='new_silver_even' "
                else:
                    bg = " class='new_silver_odd' "
                table += "<tr %s><td style='width:164px;'>%s(%s)</td>" % (bg,cnsort.fordate(days_l[xy]['days'],3),common.getxingqi(days_l[xy]['days']))
                
                for items_value in _items:
                    table += cnsort.genTableResultInc3(days_l[xy-1].get(items_value),days_l[xy].get(items_value),items_value,xy,days_l)
                table +="</tr>"
            #生成合计
            table += u"</tbody><tfoot><tr><th class='new_silver_first_n footer'>合计</th>"
            for items_value in _items:
                shu = eval("%s%s" % (items_value,'_all'))
                table += "<th style=\"text-align:right;\" class=\"footer\">%s</th>" % cnsort.num2money(shu)
                
            table += "</tr>"
            
            
            
            
            fv = {}
            
            fv['table'] = table
            fv['xianx'] = xianx
            fv['xiany'] = xiany
            fv['zongzong'] = len(days_l)
            
            fanhui[xunhuan[vxunhuan]['name']] = fv
        
        c.close()
        db.close()
            
        self.write(fanhui)
        self.finish()

class ChannelDay_beifen20120808(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        
        
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        m_value = mc.get(_md5.hexdigest()) or {}
        if settings.cache_on == 0:
            m_value = {}
        
        if not m_value:
        
        
            
            
            
            try:
                st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                return
            
            if not _pd:
                ed_time = datetime.datetime.now()
                delta = ed_time - st_time 
                _pd =  abs(delta.days)
            
            _pd = int(_pd)
            et_time = st_time + datetime.timedelta(days=_pd)
            st_datestr = st_time.strftime('%Y%m%d')
            et_datestr = et_time.strftime('%Y%m%d')
            
            all_data = []
            results = {}
            os_data = []
            
            days = []
            
            for i in xrange(0,_pd):
                now = datetime.datetime.strptime(st_datestr,'%Y%m%d')
                delta = datetime.timedelta(days=i)  
                n_days = now + delta  
                days.append(n_days.strftime('%Y%m%d'))
            
            
            if _osid == "":
                xunhuan = [{'name':'All','id':'61,59,52'},{'name':'Android','id':'61'},{'name':'iOS','id':'52'},{'name':'WP7','id':'59'}]
            elif _device_type == "":
                xunhuan = [{'name':'All','id':'1,2'},{'name':'Phone','id':'1'},{'name':'Pad','id':'2'}]
            else:
                xunhuan = [{'name':'All'}]
            
            db = connectMySQL.connMySQL_stat()
            c=db.cursor()
            
            
            json_fix = []
            sql = " SELECT vv_json FROM `channel_day_vv` where vv_json != '{}' and partner_mode in (1,2,3,8)  "
            c.execute(sql)  
            resjson = c.fetchall()
            for vl in resjson:
                strc = str(vl[0])
                arr0 = json.loads(strc)
                for key,value in arr0.items():
                    json_fix.append(key)
            json_fix = set(json_fix)
            
            fanhui = {}
            fanhui['zongji'] = "0"
            
            for vxunhuan in xrange(len(xunhuan)):
                
                zongvv_list = []
                keylist = []
                g_table = u"<div style='overflow:auto;height:200px;'><table class='new_silver_table' id='channeldayTableX' ><thead><tr><th onclick=\" tableSorting('channeldayTable', 1); \"  id='channeldayTableth1' >序号</th><th>频道</th><th>播放次数</th><th>占比</th></tr></thead>"
                str3 = {}
                tihuanriqi = "tihuanriqi"
                
                if _osid == "":
                    if _osid == "" and _device_type == "":
                        sql = "SELECT date,os_id,device_type,vv_json FROM `channel_day_vv` WHERE date >= %s and date < %s  and vv_json != '{}' and  business_type = 2 and pid_stat = 1 and os_id in (%s) and device_type in (1,2) and partner_mode in (1,2,3,8) group by date " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'])
                        sql_apiresp = "SELECT vv_json FROM `channel_day_vv` WHERE date = %s and vv_json != '{}' and  business_type = 2 and pid_stat = 1 and os_id in (%s) and device_type in (1,2) and partner_mode in (1,2,3,8) " % (tihuanriqi,xunhuan[vxunhuan]['id'])
                        sql_apiresp2 = "SELECT vv_json FROM `channel_day_vv` WHERE date = %s and vv_json != '{}' and  business_type = 2 and pid_stat = 1 and os_id in (%s) and device_type in (1,2) and partner_mode in (1,2,3,8) " % (tihuanriqi,xunhuan[vxunhuan]['id'])
                    else:
                        sql = "SELECT date,os_id,device_type,vv_json FROM `channel_day_vv` WHERE date >= %s and date < %s  and vv_json != '{}' and  business_type = 2 and pid_stat = 1 and os_id in (%s) and device_type in (%s) and partner_mode in (1,2,3,8) group by date " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type)
                        sql_apiresp = "SELECT vv_json FROM `channel_day_vv` WHERE date = %s   and vv_json != '{}' and  business_type = 2 and pid_stat = 1 and os_id in (%s) and device_type in (%s) and partner_mode in (1,2,3,8) " % (tihuanriqi,xunhuan[vxunhuan]['id'],_device_type)
                        sql_apiresp2 = "SELECT vv_json FROM `channel_day_vv` WHERE date = %s   and vv_json != '{}' and  business_type = 2 and pid_stat = 1 and os_id in (%s) and device_type in (%s) and partner_mode in (1,2,3,8) " % (tihuanriqi,xunhuan[vxunhuan]['id'],_device_type)
                elif _device_type == "":
                    sql = "SELECT date,os_id,device_type,vv_json FROM `channel_day_vv` WHERE date >= %s and date < %s  and vv_json != '{}' and  business_type = 2 and pid_stat = 1 and os_id in (%s) and device_type in (%s) and partner_mode in (1,2,3,8) group by date " % (st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'])
                    sql_apiresp = "SELECT vv_json FROM `channel_day_vv` WHERE date = %s and vv_json != '{}' and  business_type = 2 and pid_stat = 1 and os_id in (%s) and device_type in (%s) and partner_mode in (1,2,3,8)  " % (tihuanriqi,_osid,xunhuan[vxunhuan]['id'])
                    sql_apiresp2 = "SELECT vv_json FROM `channel_day_vv` WHERE date = %s and vv_json != '{}' and  business_type = 2 and pid_stat = 1 and os_id in (%s) and device_type in (%s) and partner_mode in (1,2,3,8)  " % (tihuanriqi,_osid,xunhuan[vxunhuan]['id'])
                else:
                    sql = "SELECT date,os_id,device_type,vv_json FROM `channel_day_vv` WHERE date >= %s and date < %s  and vv_json != '{}' and  business_type = 2 and pid_stat = 1 and os_id in (%s) and device_type in (%s) and partner_mode in (1,2,3,8) group by date " % (st_datestr,et_datestr,_osid,_device_type)
                    sql_apiresp = "SELECT vv_json FROM `channel_day_vv` WHERE date = %s and vv_json != '{}' and  business_type = 2 and pid_stat = 1 and os_id in (%s) and device_type in (%s) and partner_mode in (1,2,3,8)  " % (tihuanriqi,_osid,_device_type)
                    sql_apiresp2 = "SELECT vv_json FROM `channel_day_vv` WHERE date = %s and vv_json != '{}' and  business_type = 2 and pid_stat = 1 and os_id in (%s) and device_type in (%s) and partner_mode in (1,2,3,8)  " % (tihuanriqi,_osid,_device_type)
                
                
                
                c.execute(sql)  
                result_teall = c.fetchall()
                #print result_teall
                
                
                jiriqi = []
                
                for result in result_teall: 
                    jiriqi.append(str(result[0]))
                
                riqijishu = 0
                for xy in result_teall:
                    
                    
                    if riqijishu == 0:
                        sql_apiresp = sql_apiresp.replace("tihuanriqi",str(xy[0]))
                    else:
                        sql_apiresp = sql_apiresp.replace(jiriqi[riqijishu-1],str(xy[0]))

                    date = str(xy[0])
                    os = int(xy[1])
                    device_type = int(xy[2])
                    
                    
                    c.execute(sql_apiresp)  
                    result_vvj = c.fetchall()
                    
                    for fuck in result_vvj:
                    
                        vv_json = str(fuck[0])
                        arr0 = json.loads(vv_json)
                        vv = arr0.keys()
                        for ssc in json_fix:
                            if ssc not in vv:
                                arr0[ssc] = 0
                        for key,value in arr0.items():
                            str3[key] = str3.get(key,0) + value
                    
                    riqijishu = riqijishu + 1
                    
                zongjieheji = [] 
                danjieheji = []
                for key,value in str3.items():
                    keylist.append([value,key])
                    zongvv_list.append(value)
                keylist = sorted(keylist,reverse=True)
                zongvv = sum(zongvv_list)
                        
                jishu = 1
                bingtujishu = 0
                bingtu = ""
                qitashu = 0
                for x in keylist:
                    bg = ""
                    if jishu % 2 == 0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                    xianvv = str3.get(x[1])
                    a = xianvv/zongvv
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        g_table += "<tr %s ><td>%s</td><td>%s</td><td>%s</td><td>%s0%%</td></tr>" % (bg,jishu,x[1],cnsort.num2money(str3.get(x[1])),(zhanbi)*100)
                    else:
                        g_table += "<tr %s ><td>%s</td><td>%s</td><td>%s</td><td>%s%%</td></tr>" % (bg,jishu,x[1],cnsort.num2money(str3.get(x[1])),(zhanbi)*100)
                    
                    
                    zongjieheji.append(str3.get(x[1]))
                    if bingtujishu <= 8:
                        bingtu += "['%s',%s]," % (x[1],str3.get(x[1]))
                    else:
                        qitashu += str3.get(x[1])
                    jishu = jishu + 1
                    bingtujishu = bingtujishu + 1
                g_table+="</table></div>"
                bingtu += u"['OTHER',%s]," % qitashu 
                bingtu = "[%s]" % bingtu
                zongjieheji_sum = sum(zongjieheji)
                
                
                m_table = u"<div class=\"csv-box-header\"><strong>明细</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('channeldayTableX1');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('channeldayTableX1');\" >下载</a></span><a href=\"javascript:getCSVData('channeldayTableX');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>";
                    
                m_table += u"<div style='overflow:auto;height:300px;' class='bgbg'><table class='new_silver_table' id='channeldayTableX1'  ><thead><tr><th onclick=\" tableSortingly('channeldayTable', 1,1); \"  id='channeldayTableth1'  >日期</th><th>当日合计</th>"
                
                for x in keylist:
                    m_table += "<th>%s</th>" % x[1]
                m_table += "</tr></thead>"
                jishuc = 1
                days_l = []
                riqijishu = 0
                for xy in result_teall:
                    
                   
                    str3 = {}
                    date = str(xy[0])
                    os = int(xy[1])
                    device_type = int(xy[2])
                    
                    if riqijishu == 0:
                        sql_apiresp2 = sql_apiresp2.replace("tihuanriqi",str(xy[0]))
                    else:
                        sql_apiresp2 = sql_apiresp2.replace(jiriqi[riqijishu-1],str(xy[0]))
                    
                    c.execute(sql_apiresp2)  
                    result_vvj = c.fetchall()
                    
                    for fuck in result_vvj:
                    
                        vv_json = str(fuck[0])
                        arr0 = json.loads(vv_json)
                        vv = arr0.keys()
                        for ssc in json_fix:
                            if ssc not in vv:
                                arr0[ssc] = 0
                        for key,value in arr0.items():
                            str3[key] = str3.get(key,0) + value
                    
                    
                    days_l.append({'days':str(xy[0]),'cc':str3})
                    riqijishu = riqijishu + 1
                          
                for xy in xrange(len(days_l)):
                    
                    str3 = days_l[xy]['cc']
                    str5 = days_l[xy-1]['cc']
                    
                    if jishuc % 2 ==0:
                        jishucbg = " class='new_silver_even' "
                    else:
                        jishucbg = " class='new_silver_odd' "
                    
                    #m_table += "<tr %s><td>%s</td>" % (jishucbg,days_l[xy]['days'])
                    
                    m_table += "<tr %s><td>%s(%s)</td>" % (jishucbg,cnsort.fordate(days_l[xy]['days'],3),common.getxingqi(days_l[xy]['days']))
                        
                   
                    m_table_channel = ""
                        
                    jizonghe = 0
                    jizonghelastday = 0
                        
                    for x in keylist:
                            
                        lastday = str5.get(x[1])
                        nowday = str3.get(x[1])
                        cha = nowday - lastday
                            
                        if cha > 0:
                            jiantou = "<span class='inc_tag' style='margin-left: 5px;' title='0%'><b> ↑ </b></span>"
                        elif cha < 0:
                            jiantou = "<span class='des_tag' style='margin-left: 5px;' title='0%'><b> ↓ </b></span>"
                        else:
                            jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
                            
                            
                        if xy == 0:
                            jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
                            
                        m_table_channel += "<td>%s%s</td>" % (cnsort.num2money(str3.get(x[1])),jiantou)
                        jizonghe += str3.get(x[1])
                        jizonghelastday += str5.get(x[1])
                        
                        
                    lastday = jizonghelastday
                    nowday = jizonghe
                    cha = nowday - lastday
                            
                    if cha > 0:
                        jiantou = "<span class='inc_tag' style='margin-left: 5px;' title='0%'><b> ↑ </b></span>"
                    elif cha < 0:
                        jiantou = "<span class='des_tag' style='margin-left: 5px;' title='0%'><b> ↓ </b></span>"
                    else:
                        jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
                            
                            
                    if xy == 0:
                        jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
                        
                    m_table += "<td>%s%s</td>" % (cnsort.num2money(jizonghe),jiantou)
                        
                    m_table += m_table_channel
                        
                    m_table += "</tr>"
                
                    jishuc = jishuc + 1
                
                
                m_table += u"<tr><th class='new_silver_first_n footer'>总计</th><th style=\"text-align:right;\" class=\"footer\">%s</th>" % cnsort.num2money(zongjieheji_sum)
                
                for cc in zongjieheji:
                    m_table += "<th style=\"text-align:right;\" class=\"footer\">%s</th>" % cnsort.num2money(cc)
                
                m_table += "</tr>"
                  
                m_table+="</table></div>"
                  
                
                
                zong_table = "%s%s" % (g_table,m_table)
                
                
                fv = {}
                
                fv['table'] = zong_table
                fv['bingtu'] = bingtu
                
                if len(days_l) > 0:
                    fanhui['zongji'] = "1"
                
                fanhui[xunhuan[vxunhuan]['name']] = fv
            
            c.close()
            db.close()
            _url = hashlib.md5(_url)
            _url.digest()
            try:
                mc.set(key=_url.hexdigest(), val=fanhui, min_compress_len=1024*1024)
            except Exception,e:
                print e
                pass
        else:
            fanhui = m_value
            
        self.write(fanhui)
        self.finish()



class RetainVideo(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        _datetype = self.get_argument('datetype','day').strip()
        
        
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        m_value = mc.get(_md5.hexdigest()) or {}
        if settings.cache_on == 0:
            m_value = {}
        
        if not m_value:
        
            try:
                st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                return
            
            if not _pd:
                ed_time = datetime.datetime.now()
                delta = ed_time - st_time 
                _pd =  abs(delta.days)
            
            _pd = int(_pd)
            et_time = st_time + datetime.timedelta(days=_pd)
            st_datestr = st_time.strftime('%Y%m%d')
            et_datestr = et_time.strftime('%Y%m%d')
            
            all_data = []
            results = {}
            os_data = []
            
            days = []
            
            for i in xrange(0,_pd):
                now = datetime.datetime.strptime(st_datestr,'%Y%m%d')
                delta = datetime.timedelta(days=i)  
                n_days = now + delta  
                days.append(n_days.strftime('%Y%m%d'))
            
            
            if _osid == "":
                xunhuan = [{'name':'All','id':'-1'},{'name':'Android','id':'61'},{'name':'iOS','id':'52'},{'name':'WP7','id':'59'}]
            elif _device_type == "":
                xunhuan = [{'name':'All','id':'-1'},{'name':'Phone','id':'1'},{'name':'Pad','id':'2'}]
            else:
                xunhuan = [{'name':'All'}]
            
            db = connectMySQL.connMySQL_stat()
            print db
            c=db.cursor()
            
            
            
            
            fanhui = {}
            fanhui['zongji'] = "0"
                        
            for vxunhuan in xrange(len(xunhuan)):
                
                g_table = u"<div style='overflow:auto;height:300px;'><table class='new_silver_table' id='retainvideoTableX' ><thead><tr><th onclick=\" tableSorting('retainvideoTable', 1); \"  id='retainvideoTableth1' >首次使用时间</th><th>新用户</th><th>留存率</th></tr></thead>"
                
                if _datetype == "day":
                
                    if _osid == "":
                        if _osid == "" and _device_type == "":
                            sql = "SELECT date,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10) FROM `stat_retain_day_group` WHERE date >= %s and date < %s  and os_id = '%s' and device_type = '-1' and business_type = 2 group by date " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'])
                        else:
                            sql = "SELECT date,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10) FROM `stat_retain_day_group` WHERE date >= %s and date < %s  and os_id = '%s' and device_type = '%s' and business_type = 2 group by date " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type)
                    elif _device_type == "":
                        sql = "SELECT date,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10) FROM `stat_retain_day_group` WHERE date >= %s and date < %s  and os_id = '%s' and device_type = '%s' and business_type = 2 group by date " % (st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'])
                
                    else:
                        sql = "SELECT date,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10) FROM `stat_retain_day_group` WHERE date >= %s and date < %s  and os_id = '%s' and device_type = '%s' and business_type = 2 group by date " % (st_datestr,et_datestr,_osid,_device_type)
                else:
                    if _osid == "":
                        if _osid == "" and _device_type == "":
                            sql = "SELECT date_start,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10),date_end FROM `stat_retain_week_group` WHERE date_start >= %s and date_end < %s  and os_id = '%s' and device_type = '-1' and business_type = 2 group by date_end " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'])
                        else:
                            sql = "SELECT date_start,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10),date_end FROM `stat_retain_week_group` WHERE date_start >= %s and date_end < %s  and os_id = '%s' and device_type = '%s' and business_type = 2 group by date_end " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type)
                    elif _device_type == "":
                        sql = "SELECT date_start,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10),date_end FROM `stat_retain_week_group` WHERE date_start >= %s and date_end < %s  and os_id = '%s' and device_type = '%s' and business_type = 2 group by date_end " % (st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'])
                
                    else:
                        sql = "SELECT date_start,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10),date_end FROM `stat_retain_week_group` WHERE date_start >= %s and date_end < %s  and os_id = '%s' and device_type = '%s' and business_type = 2 group by date_end " % (st_datestr,et_datestr,_osid,_device_type)
              
              
                if _datetype == "day":
                    g_table += u"<tr><td></td><td></td><td><div class='verdiv'>1天后</div><div class='verdiv'>2天后</div><div class='verdiv'>3天后</div><div class='verdiv'>5天后</div><div class='verdiv'>4天后</div><div class='verdiv'>6天后</div><div class='verdiv'>7天后</div><div class='verdiv'>8天后</div></td></tr>"  
                else:
                    g_table += u"<tr><td></td><td></td><td><div class='verdiv'>1周后</div><div class='verdiv'>2周后</div><div class='verdiv'>3周后</div><div class='verdiv'>5周后</div><div class='verdiv'>4周后</div><div class='verdiv'>6周后</div><div class='verdiv'>7周后</div><div class='verdiv'>8周后</div></td></tr>" 
              
                print sql
                c.execute(sql)  
                result_teall = c.fetchall()
                
                
                jishu = 1
                for x in result_teall:
                    bg = ""
                    if jishu % 2 == 0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                    
                    
                    if _datetype == "day":
                        _date = int(x[0])
                    else:
                        _date_start = x[0]
                        _date_end = x[12]
                        
                    
                    newuser = int(x[1])
                    num_return1 = int(x[2])
                    num_return2 = int(x[3])
                    num_return3 = int(x[4])
                    num_return4 = int(x[5])
                    num_return5 = int(x[6])
                    num_return6 = int(x[7])
                    num_return7 = int(x[8])
                    num_return8 = int(x[9])
                    num_return9 = int(x[10])
                    num_return10 = int(x[11])
                    
                    try:
                        a = num_return1/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    
                    nl = str(zhanbi).split(".")
                    
                    
                    if len(str(nl[1])) < 4:
                        z1 = "%s0%%" % (zhanbi * 100)
                    else:
                        z1 = "%s%%" % (zhanbi * 100)
                    
              
                    
                    
                    
                    
                    try:
                        a = num_return2/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z2 = "%s0%%" % (zhanbi * 100)
                    else:
                        z2 = "%s%%" % (zhanbi * 100)
                    
                    
                    
                    try:
                        a = num_return3/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z3 = "%s0%%" % (zhanbi * 100)
                    else:
                        z3 = "%s%%" % (zhanbi * 100)
                    
                    try:
                        a = num_return4/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z4 = "%s0%%" % (zhanbi * 100)
                    else:
                        z4 = "%s%%" % (zhanbi * 100)
                    
                    try:
                        a = num_return5/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z5 = "%s0%%" % (zhanbi * 100)
                    else:
                        z5 = "%s%%" % (zhanbi * 100)
                    
                    try:
                        a = num_return6/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z6 = "%s0%%" % (zhanbi * 100)
                    else:
                        z6 = "%s%%" % (zhanbi * 100)
                    
                    try:
                        a = num_return7/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z7 = "%s0%%" % (zhanbi * 100)
                    else:
                        z7 = "%s%%" % (zhanbi * 100)
                    
                    try:
                        a = num_return8/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z8 = "%s0%%" % (zhanbi * 100)
                    else:
                        z8 = "%s%%" % (zhanbi * 100)
                    
                    try:
                        a = num_return9/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z9 = "%s0%%" % (zhanbi * 100)
                    else:
                        z9 = "%s%%" % (zhanbi * 100)
                    
                    try:
                        a = num_return10/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z10 = "%s0%%" % (zhanbi * 100)
                    else:
                        z10 = "%s%%" % (zhanbi * 100)
                        
                    
                    
                    if _datetype == "day":
                        _datestr = _date
                    else:
                        _datestr = "%s-%s" % (_date_start,_date_end) 
                    
                    
                    #print z1
                    
                    g_table += "<tr %s ><td>%s</td><td>%s</td><td><div class='verdiv'>%s</div><div class='verdiv'>%s</div><div class='verdiv'>%s</div><div class='verdiv'>%s</div><div class='verdiv'>%s</div><div class='verdiv'>%s</div><div class='verdiv'>%s</div><div class='verdiv'>%s</div></td></tr>" % (bg,_datestr,newuser,z1,z2,z3,z4,z5,z6,z7,z8)
                    
                    jishu = jishu + 1


                
                g_table+="</table></div>"
                
                
                
                fv = {}
                
                fv['table'] = g_table
                
                #print len(result_teall)
                if len(result_teall) > 0:
                    fanhui['zongji'] = "1"
                
                fanhui[xunhuan[vxunhuan]['name']] = fv
            
            c.close()
            db.close()
            _url = hashlib.md5(_url)
            _url.digest()
            try:
                mc.set(key=_url.hexdigest(), val=fanhui, min_compress_len=1024*1024)
            except Exception,e:
                print e
                pass
        else:
            fanhui = m_value
            
        self.write(fanhui)
        self.finish()
        


class RetainPaike(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        _datetype = self.get_argument('datetype','day').strip()
        
        
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        m_value = mc.get(_md5.hexdigest()) or {}
        if settings.cache_on == 0:
            m_value = {}
        
        if not m_value:
        
            try:
                st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                return
            
            if not _pd:
                ed_time = datetime.datetime.now()
                delta = ed_time - st_time 
                _pd =  abs(delta.days)
            
            _pd = int(_pd)
            et_time = st_time + datetime.timedelta(days=_pd)
            st_datestr = st_time.strftime('%Y%m%d')
            et_datestr = et_time.strftime('%Y%m%d')
            
            all_data = []
            results = {}
            os_data = []
            
            days = []
            
            for i in xrange(0,_pd):
                now = datetime.datetime.strptime(st_datestr,'%Y%m%d')
                delta = datetime.timedelta(days=i)  
                n_days = now + delta  
                days.append(n_days.strftime('%Y%m%d'))
            
            
            if _osid == "":
                xunhuan = [{'name':'All','id':'-1'},{'name':'Android','id':'61'},{'name':'iOS','id':'52'},{'name':'WP7','id':'59'}]
            elif _device_type == "":
                xunhuan = [{'name':'All','id':'-1'},{'name':'Phone','id':'1'},{'name':'Pad','id':'2'}]
            else:
                xunhuan = [{'name':'All'}]
            
            db = connectMySQL.connMySQL_stat()
            c=db.cursor()
            
            
            
            
            fanhui = {}
            fanhui['zongji'] = "0"
                        
            for vxunhuan in xrange(len(xunhuan)):
                
                g_table = u"<div style='overflow:auto;height:300px;'><table class='new_silver_table' id='retainpaikeTableX' ><thead><tr><th onclick=\" tableSorting('retainpaikeTable', 1); \"  id='retainpaikeTableth1' >首次使用时间</th><th>新用户</th><th>留存率</th></tr></thead>"
                
                if _datetype == "day":
                
                    if _osid == "":
                        if _osid == "" and _device_type == "":
                            sql = "SELECT date,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10) FROM `stat_retain_day_group` WHERE date >= %s and date < %s  and os_id = '%s' and device_type = '-1' and business_type = 4 group by date " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'])
                        else:
                            sql = "SELECT date,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10) FROM `stat_retain_day_group` WHERE date >= %s and date < %s  and os_id = '%s' and device_type = '%s' and business_type = 4 group by date " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type)
                    elif _device_type == "":
                        sql = "SELECT date,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10) FROM `stat_retain_day_group` WHERE date >= %s and date < %s  and os_id = '%s' and device_type = '%s' and business_type = 4 group by date " % (st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'])
                
                    else:
                        sql = "SELECT date,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10) FROM `stat_retain_day_group` WHERE date >= %s and date < %s  and os_id = '%s' and device_type = '%s' and business_type = 4 group by date " % (st_datestr,et_datestr,_osid,_device_type)
                else:
                    if _osid == "":
                        if _osid == "" and _device_type == "":
                            sql = "SELECT date_start,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10),date_end FROM `stat_retain_week_group` WHERE date_start >= %s and date_end < %s  and os_id = '%s' and device_type = '-1' and business_type = 4 group by date_end " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'])
                        else:
                            sql = "SELECT date_start,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10),date_end FROM `stat_retain_week_group` WHERE date_start >= %s and date_end < %s  and os_id = '%s' and device_type = '%s' and business_type = 4 group by date_end " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type)
                    elif _device_type == "":
                        sql = "SELECT date_start,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10),date_end FROM `stat_retain_week_group` WHERE date_start >= %s and date_end < %s  and os_id = '%s' and device_type = '%s' and business_type = 4 group by date_end " % (st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'])
                
                    else:
                        sql = "SELECT date_start,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10),date_end FROM `stat_retain_week_group` WHERE date_start >= %s and date_end < %s  and os_id = '%s' and device_type = '%s' and business_type = 4 group by date_end " % (st_datestr,et_datestr,_osid,_device_type)
              
              
                if _datetype == "day":
                    g_table += u"<tr><td></td><td></td><td><div class='verdiv'>1天后</div><div class='verdiv'>2天后</div><div class='verdiv'>3天后</div><div class='verdiv'>5天后</div><div class='verdiv'>4天后</div><div class='verdiv'>6天后</div><div class='verdiv'>7天后</div><div class='verdiv'>8天后</div></td></tr>"  
                else:
                    g_table += u"<tr><td></td><td></td><td><div class='verdiv'>1周后</div><div class='verdiv'>2周后</div><div class='verdiv'>3周后</div><div class='verdiv'>5周后</div><div class='verdiv'>4周后</div><div class='verdiv'>6周后</div><div class='verdiv'>7周后</div><div class='verdiv'>8周后</div></td></tr>" 
              
                print sql
                c.execute(sql)  
                result_teall = c.fetchall()
                
                
                jishu = 1
                for x in result_teall:
                    bg = ""
                    if jishu % 2 == 0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                    
                    
                    if _datetype == "day":
                        _date = int(x[0])
                    else:
                        _date_start = x[0]
                        _date_end = x[12]
                        
                    
                    newuser = int(x[1])
                    num_return1 = int(x[2])
                    num_return2 = int(x[3])
                    num_return3 = int(x[4])
                    num_return4 = int(x[5])
                    num_return5 = int(x[6])
                    num_return6 = int(x[7])
                    num_return7 = int(x[8])
                    num_return8 = int(x[9])
                    num_return9 = int(x[10])
                    num_return10 = int(x[11])
                    
                    try:
                        a = num_return1/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    
                    nl = str(zhanbi).split(".")
                    
                    
                    if len(str(nl[1])) < 4:
                        z1 = "%s0%%" % (zhanbi * 100)
                    else:
                        z1 = "%s%%" % (zhanbi * 100)
                    
              
                    
                    
                    
                    
                    try:
                        a = num_return2/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z2 = "%s0%%" % (zhanbi * 100)
                    else:
                        z2 = "%s%%" % (zhanbi * 100)
                    
                    
                    
                    try:
                        a = num_return3/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z3 = "%s0%%" % (zhanbi * 100)
                    else:
                        z3 = "%s%%" % (zhanbi * 100)
                    
                    try:
                        a = num_return4/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z4 = "%s0%%" % (zhanbi * 100)
                    else:
                        z4 = "%s%%" % (zhanbi * 100)
                    
                    try:
                        a = num_return5/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z5 = "%s0%%" % (zhanbi * 100)
                    else:
                        z5 = "%s%%" % (zhanbi * 100)
                    
                    try:
                        a = num_return6/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z6 = "%s0%%" % (zhanbi * 100)
                    else:
                        z6 = "%s%%" % (zhanbi * 100)
                    
                    try:
                        a = num_return7/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z7 = "%s0%%" % (zhanbi * 100)
                    else:
                        z7 = "%s%%" % (zhanbi * 100)
                    
                    try:
                        a = num_return8/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z8 = "%s0%%" % (zhanbi * 100)
                    else:
                        z8 = "%s%%" % (zhanbi * 100)
                    
                    try:
                        a = num_return9/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z9 = "%s0%%" % (zhanbi * 100)
                    else:
                        z9 = "%s%%" % (zhanbi * 100)
                    
                    try:
                        a = num_return10/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z10 = "%s0%%" % (zhanbi * 100)
                    else:
                        z10 = "%s%%" % (zhanbi * 100)
                        
                    
                    
                    if _datetype == "day":
                        _datestr = _date
                    else:
                        _datestr = "%s-%s" % (_date_start,_date_end) 
                    
                    
                    #print z1
                    
                    g_table += "<tr %s ><td>%s</td><td>%s</td><td><div class='verdiv'>%s</div><div class='verdiv'>%s</div><div class='verdiv'>%s</div><div class='verdiv'>%s</div><div class='verdiv'>%s</div><div class='verdiv'>%s</div><div class='verdiv'>%s</div><div class='verdiv'>%s</div></td></tr>" % (bg,_datestr,newuser,z1,z2,z3,z4,z5,z6,z7,z8)
                    
                    jishu = jishu + 1


                
                g_table+="</table></div>"
                
                
                
                fv = {}
                
                fv['table'] = g_table
                
                
                if len(result_teall) > 0:
                    fanhui['zongji'] = "1"
                
                fanhui[xunhuan[vxunhuan]['name']] = fv
            
            c.close()
            db.close()
            _url = hashlib.md5(_url)
            _url.digest()
            try:
                mc.set(key=_url.hexdigest(), val=fanhui, min_compress_len=1024*1024)
            except Exception,e:
                print e
                pass
        else:
            fanhui = m_value
            
        self.write(fanhui)
        self.finish()




class Return_Tudou_Video(BaseHandler):
        
    def get(self): 
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','10').strip()
        _osid = self.get_argument('os','61,52,59').strip()
        _device_type = self.get_argument('dt','1,2').strip()
        
        
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        m_value = mc.get(_md5.hexdigest()) or {}
        if settings.cache_on == 0:
            m_value = {}
        m_value = {}
        
        if not m_value:
        
            try:
                st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                return
            
            if not _pd:
                ed_time = datetime.datetime.now()
                delta = ed_time - st_time 
                _pd =  abs(delta.days)
            
            _pd = int(_pd)
            et_time = st_time + datetime.timedelta(days=_pd)
            st_datestr = st_time.strftime('%Y%m%d')
            et_datestr = et_time.strftime('%Y%m%d')
            
            all_data = []
            results = {}
            os_data = []
            
            days = []
            
            for i in xrange(0,_pd):
                now = datetime.datetime.strptime(st_datestr,'%Y%m%d')
                delta = datetime.timedelta(days=i)  
                n_days = now + delta  
                days.append(n_days.strftime('%Y%m%d'))
            
            
            
            xunhuan = [{'name':'All'}]
            
            db = connectMySQL.connMySQL_stat()
            c=db.cursor()
            
            
            
            
            fanhui = {}
            
            fanhui['Status'] = "success"
            
            riqis = str(st_datestr)
            yy = riqis[0:4]
            mm = riqis[4:6]
            dd = riqis[6:]
                        
            for vxunhuan in xrange(len(xunhuan)):
                
                
                sql = "SELECT date,sum(vv),sum(uv),sum(newuser),sum(duration)  FROM `stat_day_total_collect` WHERE date = %s   and  business_type=2 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (1,2,3,8) and ver = 'ALL' and prov = 'ALL' and city = 'ALL'" % (st_datestr,_osid,_device_type) 
                
                print sql
                c.execute(sql)  
                result_teall = c.fetchall()
                
                for x in result_teall:
                    
                    if x[0] == None:
                        
                        shuju = "No Data"
                        
                    else:
                    
                        _date = x[0]
                        _vv = int(x[1])
                        _uv = int(x[2])
                        _nu = int(x[3])
                        _dur = int(x[4])
                        
                        _dur = _dur / 60
                        
                        
                        
                        shuju = {}
                        shuju['vv'] = _vv
                        shuju['uv'] = _uv
                        shuju['nu'] = _nu
                        shuju['dur'] = _dur
                    
                    _items = {}
                    _items['Year'] = yy
                    _items['Month'] = mm
                    _items['Day'] = dd
                    _items['Data'] = shuju
                    fanhui['Items'] = _items
                    
                
                #if len(result_teall) > 0:
                #    fanhui['zongji'] = "1"
            
            c.close()
            db.close()
            _url = hashlib.md5(_url)
            _url.digest()
            try:
                mc.set(key=_url.hexdigest(), val=fanhui, min_compress_len=1024*1024)
            except Exception,e:
                print e
                pass
        else:
            fanhui = m_value
            
        #self.set_header("Content-Type", "text/json;charset=UTF-8")
        self.write(fanhui)
        self.finish()
        
        
class Return_Tudou_Paike(BaseHandler):
        
    def get(self): 
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','10').strip()
        _osid = self.get_argument('os','61,52,59').strip()
        _device_type = self.get_argument('dt','1,2').strip()
        
        
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        m_value = mc.get(_md5.hexdigest()) or {}
        if settings.cache_on == 0:
            m_value = {}
        m_value = {}
        if not m_value:
        
            try:
                st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                return
            
            if not _pd:
                ed_time = datetime.datetime.now()
                delta = ed_time - st_time 
                _pd =  abs(delta.days)
            
            _pd = int(_pd)
            et_time = st_time + datetime.timedelta(days=_pd)
            st_datestr = st_time.strftime('%Y%m%d')
            et_datestr = et_time.strftime('%Y%m%d')
            
            all_data = []
            results = {}
            os_data = []
            
            days = []
            
            for i in xrange(0,_pd):
                now = datetime.datetime.strptime(st_datestr,'%Y%m%d')
                delta = datetime.timedelta(days=i)  
                n_days = now + delta  
                days.append(n_days.strftime('%Y%m%d'))
            
            
            
            xunhuan = [{'name':'All'}]
            
            db = connectMySQL.connMySQL_stat()
            c=db.cursor()
            
            
            
            
            fanhui = {}
            
            fanhui['Status'] = "success"
            
            riqis = str(st_datestr)
            yy = riqis[0:4]
            mm = riqis[4:6]
            dd = riqis[6:]
                        
            for vxunhuan in xrange(len(xunhuan)):
                
                
                sql = "SELECT date,sum(vv),sum(uv),sum(newuser),sum(upload),sum(total_uploads)  FROM `stat_day_paike_collect` WHERE date = %s   and  business_type=4 and pid_stat=1 and os_id in (%s) and device_type in (%s) and partner_mode in (1,2,3,8) and ver = 'ALL' and prov = 'ALL' and city = 'ALL'" % (st_datestr,_osid,_device_type) 
                
                print sql
                c.execute(sql)  
                result_teall = c.fetchall()
                
                for x in result_teall:
                    
                    if x[0] == None:
                        shuju = "No Data"
                    else:
                        _date = x[0]
                        _vv = int(x[1])
                        _uv = int(x[2])
                        _nu = int(x[3])
                        _su = int(x[4])
                        _tu = int(x[5])
                        
                        
                        shuju = {}
                        shuju['vv'] = _vv
                        shuju['uv'] = _uv
                        shuju['nu'] = _nu
                        shuju['su'] = _su
                        shuju['tu'] = _tu
                    
                    _items = {}
                    _items['Year'] = yy
                    _items['Month'] = mm
                    _items['Day'] = dd
                    _items['Data'] = shuju
                    fanhui['Items'] = _items
                    
                
                
                
                
                #if len(result_teall) > 0:
                #    fanhui['zongji'] = "1"
            
            c.close()
            db.close()
            _url = hashlib.md5(_url)
            _url.digest()
            try:
                mc.set(key=_url.hexdigest(), val=fanhui, min_compress_len=1024*1024)
            except Exception,e:
                print e
                pass
        else:
            fanhui = m_value
        
        self.set_header("Content-Type", "text/json;charset=UTF-8")
        self.write(fanhui)
        self.finish()



        
        
class RetainFactory(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        _datetype = self.get_argument('datetype','day').strip()
        
        _f_id = self.get_argument('f_id','').strip()
        
        if _f_id != "": 
            f_id_sql = " and f_id = %s " % _f_id
        else:
            f_id_sql = " "
        
        
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        m_value = mc.get(_md5.hexdigest()) or {}
        if settings.cache_on == 0:
            m_value = {}
        
        if not m_value:
        
            try:
                st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                return
            
            if not _pd:
                ed_time = datetime.datetime.now()
                delta = ed_time - st_time 
                _pd =  abs(delta.days)
            
            _pd = int(_pd)
            et_time = st_time + datetime.timedelta(days=_pd)
            st_datestr = st_time.strftime('%Y%m%d')
            et_datestr = et_time.strftime('%Y%m%d')
            
            all_data = []
            results = {}
            os_data = []
            
            days = []
            
            for i in xrange(0,_pd):
                now = datetime.datetime.strptime(st_datestr,'%Y%m%d')
                delta = datetime.timedelta(days=i)  
                n_days = now + delta  
                days.append(n_days.strftime('%Y%m%d'))
            
            
            if _osid == "":
                xunhuan = [{'name':'All','id':'61,52,59'},{'name':'Android','id':'61'},{'name':'iOS','id':'52'},{'name':'WP7','id':'59'}]
            elif _device_type == "":
                xunhuan = [{'name':'All','id':'1,2'},{'name':'Phone','id':'1'},{'name':'Pad','id':'2'}]
            else:
                xunhuan = [{'name':'All'}]
            
            db = connectMySQL.connMySQL_stat()
            c=db.cursor()
            
            
            
            fanhui = {}
            fanhui['zongji'] = "0"
                        
            for vxunhuan in xrange(len(xunhuan)):
                
                g_table = u"<div style='overflow:auto;height:300px;'><table class='new_silver_table' id='retainfactoryTableX' ><thead><tr><th class='new_silver_first_n asc_table' onclick=\" tableSorting('retainfactoryTable', 1); \"  id='retainfactoryTableth1' >首次使用时间</th><th>新用户</th><th>留存率</th></tr></thead>"
                
                if _datetype == "day":
                
                    if _osid == "":
                        if _osid == "" and _device_type == "":
                            sql = "SELECT date,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10) FROM `stat_retain_day` WHERE date >= %s and date < %s  and os_id in (%s) and device_type = 1 and partner_mode  = 1 and business_type in (2,4) and pid_stat = 1 %s group by date order by date asc " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],f_id_sql)
                        else:
                            sql = "SELECT date,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10) FROM `stat_retain_day` WHERE date >= %s and date < %s  and os_id in (%s) and device_type in (%s) and partner_mode  = 1 and business_type in (2,4) and pid_stat = 1 %s group by date order by date asc " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type,f_id_sql)
                    elif _device_type == "":
                        sql = "SELECT date,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10) FROM `stat_retain_day` WHERE date >= %s and date < %s  and os_id in (%s) and device_type in (%s) and partner_mode  = 1 and business_type in (2,4) and pid_stat = 1 %s group by date order by date asc " % (st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'],f_id_sql)
                
                    else:
                        sql = "SELECT date,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10) FROM `stat_retain_day` WHERE date >= %s and date < %s  and os_id in (%s) and device_type in (%s) and partner_mode  = 1 and business_type in (2,4) and pid_stat = 1 %s group by date order by date asc " % (st_datestr,et_datestr,_osid,_device_type,f_id_sql)
                else:
                    if _osid == "":
                        if _osid == "" and _device_type == "":
                            sql = "SELECT date_start,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10),date_end FROM `stat_retain_week` WHERE date_start >= %s and date_end < %s  and os_id in (%s) and device_type = 1 and partner_mode  = 1 and business_type in (2,4) and pid_stat = 1 %s group by date_end order by date_end asc " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],f_id_sql)
                        else:
                            sql = "SELECT date_start,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10),date_end FROM `stat_retain_week` WHERE date_start >= %s and date_end < %s  and os_id in (%s) and device_type in (%s) and partner_mode  = 1 and business_type in (2,4) and pid_stat = 1 %s group by date_end order by date_end asc " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type,f_id_sql)
                    elif _device_type == "":
                        sql = "SELECT date_start,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10),date_end FROM `stat_retain_week` WHERE date_start >= %s and date_end < %s  and os_id in (%s) and device_type in (%s) and partner_mode  = 1 and business_type in (2,4) and pid_stat = 1 %s group by date_end order by date_end asc " % (st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'],f_id_sql)
                
                    else:
                        sql = "SELECT date_start,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10),date_end FROM `stat_retain_week` WHERE date_start >= %s and date_end < %s  and os_id in (%s) and device_type in (%s) and partner_mode  = 1 and business_type in (2,4) and pid_stat = 1 %s group by date_end order by date_end asc " % (st_datestr,et_datestr,_osid,_device_type,f_id_sql)
              
              
                if _datetype == "day":
                    g_table += u"<tr><td></td><td></td><td><div class='verdiv'>1天后</div><div class='verdiv'>2天后</div><div class='verdiv'>3天后</div><div class='verdiv'>4天后</div><div class='verdiv'>5天后</div><div class='verdiv'>6天后</div><div class='verdiv'>7天后</div><div class='verdiv'>8天后</div></td></tr>"  
                else:
                    g_table += u"<tr><td></td><td></td><td><div class='verdiv'>1周后</div><div class='verdiv'>2周后</div><div class='verdiv'>3周后</div><div class='verdiv'>4周后</div><div class='verdiv'>5周后</div><div class='verdiv'>6周后</div><div class='verdiv'>7周后</div><div class='verdiv'>8周后</div></td></tr>" 
              
                print sql
                c.execute(sql)  
                result_teall = c.fetchall()
                
                
                jishu = 1
                for x in result_teall:
                    bg = ""
                    if jishu % 2 == 0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                    
                    
                    if _datetype == "day":
                        _date = int(x[0])
                    else:
                        _date_start = x[0]
                        _date_end = x[12]
                        
                    
                    newuser = int(x[1])
                    num_return1 = int(x[2])
                    num_return2 = int(x[3])
                    num_return3 = int(x[4])
                    num_return4 = int(x[5])
                    num_return5 = int(x[6])
                    num_return6 = int(x[7])
                    num_return7 = int(x[8])
                    num_return8 = int(x[9])
                    num_return9 = int(x[10])
                    num_return10 = int(x[11])
                    
                    try:
                        a = num_return1/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    
                    nl = str(zhanbi).split(".")
                    
                    
                    if len(str(nl[1])) < 4:
                        z1 = "%s0%%" % (zhanbi * 100)
                    else:
                        z1 = "%s%%" % (zhanbi * 100)
                    
              
                    
                    
                    
                    
                    try:
                        a = num_return2/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z2 = "%s0%%" % (zhanbi * 100)
                    else:
                        z2 = "%s%%" % (zhanbi * 100)
                    
                    
                    
                    try:
                        a = num_return3/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z3 = "%s0%%" % (zhanbi * 100)
                    else:
                        z3 = "%s%%" % (zhanbi * 100)
                    
                    try:
                        a = num_return4/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z4 = "%s0%%" % (zhanbi * 100)
                    else:
                        z4 = "%s%%" % (zhanbi * 100)
                    
                    try:
                        a = num_return5/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z5 = "%s0%%" % (zhanbi * 100)
                    else:
                        z5 = "%s%%" % (zhanbi * 100)
                    
                    try:
                        a = num_return6/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z6 = "%s0%%" % (zhanbi * 100)
                    else:
                        z6 = "%s%%" % (zhanbi * 100)
                    
                    try:
                        a = num_return7/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z7 = "%s0%%" % (zhanbi * 100)
                    else:
                        z7 = "%s%%" % (zhanbi * 100)
                    
                    try:
                        a = num_return8/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z8 = "%s0%%" % (zhanbi * 100)
                    else:
                        z8 = "%s%%" % (zhanbi * 100)
                    
                    try:
                        a = num_return9/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z9 = "%s0%%" % (zhanbi * 100)
                    else:
                        z9 = "%s%%" % (zhanbi * 100)
                    
                    try:
                        a = num_return10/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z10 = "%s0%%" % (zhanbi * 100)
                    else:
                        z10 = "%s%%" % (zhanbi * 100)
                        
                    
                    
                    if _datetype == "day":
                        _datestr = _date
                    else:
                        _datestr = "%s-%s" % (_date_start,_date_end) 
                    
                    
                    #print z1
                    
                    g_table += "<tr %s ><td>%s</td><td>%s</td><td><div class='verdiv'>%s</div><div class='verdiv'>%s</div><div class='verdiv'>%s</div><div class='verdiv'>%s</div><div class='verdiv'>%s</div><div class='verdiv'>%s</div><div class='verdiv'>%s</div><div class='verdiv'>%s</div></td></tr>" % (bg,_datestr,newuser,z1,z2,z3,z4,z5,z6,z7,z8)
                    
                    jishu = jishu + 1


                
                g_table+="</table></div>"
                
                
                
                fv = {}
                
                fv['table'] = g_table
                
                
                if len(result_teall) > 0:
                    fanhui['zongji'] = "1"
                
                fanhui[xunhuan[vxunhuan]['name']] = fv
            
            c.close()
            db.close()
            _url = hashlib.md5(_url)
            _url.digest()
            try:
                mc.set(key=_url.hexdigest(), val=fanhui, min_compress_len=1024*1024)
            except Exception,e:
                print e
                pass
        else:
            fanhui = m_value
            
        self.write(fanhui)
        self.finish()
        

class RetainChannel(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        _datetype = self.get_argument('datetype','day').strip()
        
        _f_id = self.get_argument('f_id','').strip()
        
        if _f_id != "": 
            f_id_sql = " and f_id = %s " % _f_id
        else:
            f_id_sql = " "
            
            
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        m_value = mc.get(_md5.hexdigest()) or {}
        if settings.cache_on == 0:
            m_value = {}
        
        if not m_value:
        
            try:
                st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                return
            
            if not _pd:
                ed_time = datetime.datetime.now()
                delta = ed_time - st_time 
                _pd =  abs(delta.days)
            
            _pd = int(_pd)
            et_time = st_time + datetime.timedelta(days=_pd)
            st_datestr = st_time.strftime('%Y%m%d')
            et_datestr = et_time.strftime('%Y%m%d')
            
            all_data = []
            results = {}
            os_data = []
            
            days = []
            
            for i in xrange(0,_pd):
                now = datetime.datetime.strptime(st_datestr,'%Y%m%d')
                delta = datetime.timedelta(days=i)  
                n_days = now + delta  
                days.append(n_days.strftime('%Y%m%d'))
            
            
            if _osid == "":
                xunhuan = [{'name':'All','id':'61,52,59'},{'name':'Android','id':'61'},{'name':'iOS','id':'52'},{'name':'WP7','id':'59'}]
            elif _device_type == "":
                xunhuan = [{'name':'All','id':'1,2'},{'name':'Phone','id':'1'},{'name':'Pad','id':'2'}]
            else:
                xunhuan = [{'name':'All'}]
            
            db = connectMySQL.connMySQL_stat()
            c=db.cursor()
            
            
            
            fanhui = {}
            fanhui['zongji'] = "0"
                        
            for vxunhuan in xrange(len(xunhuan)):
                
                g_table = u"<div style='overflow:auto;height:300px;'><table class='new_silver_table' id='retainchannelTableX' ><thead><tr><th onclick=\" tableSorting('retainchannelTable', 1); \"  id='retainchannelTableth1' >首次使用时间</th><th>新用户</th><th>留存率</th></tr></thead>"
                
                if _datetype == "day":
                
                    if _osid == "":
                        if _osid == "" and _device_type == "":
                            sql = "SELECT date,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10) FROM `stat_retain_day` WHERE date >= %s and date < %s  and os_id in (%s) and device_type = 1 and partner_mode  in (2,8) and business_type in (2,4) and pid_stat = 1 %s group by date order by date asc " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],f_id_sql)
                        else:
                            sql = "SELECT date,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10) FROM `stat_retain_day` WHERE date >= %s and date < %s  and os_id in (%s) and device_type in (%s) and partner_mode  in (2,8) and business_type in (2,4) and pid_stat = 1 %s group by date order by date asc " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type,f_id_sql)
                    elif _device_type == "":
                        sql = "SELECT date,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10) FROM `stat_retain_day` WHERE date >= %s and date < %s  and os_id in (%s) and device_type in (%s) and partner_mode  in (2,8) and business_type in (2,4) and pid_stat = 1 %s group by date order by date asc " % (st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'],f_id_sql)
                
                    else:
                        sql = "SELECT date,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10) FROM `stat_retain_day` WHERE date >= %s and date < %s  and os_id in (%s) and device_type in (%s) and partner_mode  in (2,8) and business_type in (2,4) and pid_stat = 1 %s group by date order by date asc " % (st_datestr,et_datestr,_osid,_device_type,f_id_sql)
                else:
                    if _osid == "":
                        if _osid == "" and _device_type == "":
                            sql = "SELECT date_start,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10),date_end FROM `stat_retain_week` WHERE date_start >= %s and date_end < %s  and os_id in (%s) and device_type = 1 and partner_mode  in (2,8) and pid_stat = 1 %s and business_type in (2,4) group by date_end order by date_end asc " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],f_id_sql)
                        else:
                            sql = "SELECT date_start,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10),date_end FROM `stat_retain_week` WHERE date_start >= %s and date_end < %s  and os_id in (%s) and device_type in (%s) and partner_mode  in (2,8) and business_type in (2,4) and pid_stat = 1 %s group by date_end order by date_end asc " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type,f_id_sql)
                    elif _device_type == "":
                        sql = "SELECT date_start,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10),date_end FROM `stat_retain_week` WHERE date_start >= %s and date_end < %s  and os_id in (%s) and device_type in (%s) and partner_mode  in (2,8) and business_type in (2,4) and pid_stat = 1 %s group by date_end order by date_end asc " % (st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'],f_id_sql)
                
                    else:
                        sql = "SELECT date_start,sum(newuser),sum(num_return1),sum(num_return2),sum(num_return3),sum(num_return4),sum(num_return5),sum(num_return6),sum(num_return7),sum(num_return8),sum(num_return9),sum(num_return10),date_end FROM `stat_retain_week` WHERE date_start >= %s and date_end < %s  and os_id in (%s) and device_type in (%s) and partner_mode  in (2,8) and business_type in (2,4) and pid_stat = 1 %s group by date_end order by date_end asc " % (st_datestr,et_datestr,_osid,_device_type,f_id_sql)
              
              
                if _datetype == "day":
                    g_table += u"<tr><td></td><td></td><td><div class='verdiv'>1天后</div><div class='verdiv'>2天后</div><div class='verdiv'>3天后</div><div class='verdiv'>4天后</div><div class='verdiv'>5天后</div><div class='verdiv'>6天后</div><div class='verdiv'>7天后</div><div class='verdiv'>8天后</div></td></tr>"  
                else:
                    g_table += u"<tr><td></td><td></td><td><div class='verdiv'>1周后</div><div class='verdiv'>2周后</div><div class='verdiv'>3周后</div><div class='verdiv'>4周后</div><div class='verdiv'>5周后</div><div class='verdiv'>6周后</div><div class='verdiv'>7周后</div><div class='verdiv'>8周后</div></td></tr>" 
              
                print sql
                c.execute(sql)  
                result_teall = c.fetchall()
                
                
                jishu = 1
                for x in result_teall:
                    bg = ""
                    if jishu % 2 == 0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                    
                    
                    if _datetype == "day":
                        _date = int(x[0])
                    else:
                        _date_start = x[0]
                        _date_end = x[12]
                        
                    
                    newuser = int(x[1])
                    num_return1 = int(x[2])
                    num_return2 = int(x[3])
                    num_return3 = int(x[4])
                    num_return4 = int(x[5])
                    num_return5 = int(x[6])
                    num_return6 = int(x[7])
                    num_return7 = int(x[8])
                    num_return8 = int(x[9])
                    num_return9 = int(x[10])
                    num_return10 = int(x[11])
                    
                    try:
                        a = num_return1/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    
                    nl = str(zhanbi).split(".")
                    
                    
                    if len(str(nl[1])) < 4:
                        z1 = "%s0%%" % (zhanbi * 100)
                    else:
                        z1 = "%s%%" % (zhanbi * 100)
                    
              
                    
                    
                    
                    
                    try:
                        a = num_return2/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z2 = "%s0%%" % (zhanbi * 100)
                    else:
                        z2 = "%s%%" % (zhanbi * 100)
                    
                    
                    
                    try:
                        a = num_return3/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z3 = "%s0%%" % (zhanbi * 100)
                    else:
                        z3 = "%s%%" % (zhanbi * 100)
                    
                    try:
                        a = num_return4/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z4 = "%s0%%" % (zhanbi * 100)
                    else:
                        z4 = "%s%%" % (zhanbi * 100)
                    
                    try:
                        a = num_return5/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z5 = "%s0%%" % (zhanbi * 100)
                    else:
                        z5 = "%s%%" % (zhanbi * 100)
                    
                    try:
                        a = num_return6/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z6 = "%s0%%" % (zhanbi * 100)
                    else:
                        z6 = "%s%%" % (zhanbi * 100)
                    
                    try:
                        a = num_return7/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z7 = "%s0%%" % (zhanbi * 100)
                    else:
                        z7 = "%s%%" % (zhanbi * 100)
                    
                    try:
                        a = num_return8/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z8 = "%s0%%" % (zhanbi * 100)
                    else:
                        z8 = "%s%%" % (zhanbi * 100)
                    
                    try:
                        a = num_return9/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z9 = "%s0%%" % (zhanbi * 100)
                    else:
                        z9 = "%s%%" % (zhanbi * 100)
                    
                    try:
                        a = num_return10/newuser
                    except:
                        a = 0
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        z10 = "%s0%%" % (zhanbi * 100)
                    else:
                        z10 = "%s%%" % (zhanbi * 100)
                        
                    
                    
                    if _datetype == "day":
                        _datestr = _date
                    else:
                        _datestr = "%s-%s" % (_date_start,_date_end) 
                    
                    
                    #print z1
                    
                    g_table += "<tr %s ><td>%s</td><td>%s</td><td><div class='verdiv'>%s</div><div class='verdiv'>%s</div><div class='verdiv'>%s</div><div class='verdiv'>%s</div><div class='verdiv'>%s</div><div class='verdiv'>%s</div><div class='verdiv'>%s</div><div class='verdiv'>%s</div></td></tr>" % (bg,_datestr,newuser,z1,z2,z3,z4,z5,z6,z7,z8)
                    
                    jishu = jishu + 1


                
                g_table+="</table></div>"
                
                
                
                fv = {}
                
                fv['table'] = g_table
                
                
                if len(result_teall) > 0:
                    fanhui['zongji'] = "1"
                
                fanhui[xunhuan[vxunhuan]['name']] = fv
            
            c.close()
            db.close()
            _url = hashlib.md5(_url)
            _url.digest()
            try:
                mc.set(key=_url.hexdigest(), val=fanhui, min_compress_len=1024*1024)
            except Exception,e:
                print e
                pass
        else:
            fanhui = m_value
            
        self.write(fanhui)
        self.finish()
        
        
class ProDownload(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        mark_id = self.get_argument('mark_id','all').strip()
        client_id = self.get_argument('client_id','all').strip()
        date_type = self.get_argument('date_type','day').strip()
        
        mark_item = []
        if mark_id == "all":
            mark_item = ['1','2','3','4','5','6','7']
        else:
            mark_item.append(mark_id)
        
        client_item = []
        
        if client_id == "all":
            client_item = ['1','2','3','4','5']
        else:
            client_item.append(client_id)
        
        #print client_item
            
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        m_value = mc.get(_md5.hexdigest()) or {}
        #if settings.cache_on == 0:
        m_value = {}
        
        if not m_value:
        
            try:
                st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                return
            
            if not _pd:
                ed_time = datetime.datetime.now()
                delta = ed_time - st_time 
                _pd =  abs(delta.days)
            
            _pd = int(_pd)
            et_time = st_time + datetime.timedelta(days=_pd)
            st_datestr = st_time.strftime('%Y%m%d')
            et_datestr = et_time.strftime('%Y%m%d')
            
            all_data = []
            results = {}
            os_data = []
            
            
            
            
            
            xunhuan = [{'name':'All'}]
            
            db = connectMySQL.connMySQL_stat()
            c=db.cursor()
            
            
            
            fanhui = {}
            fanhui['zongji'] = "0"
                        
            for vxunhuan in xrange(len(xunhuan)):
                
                #g_table = u"<div style='overflow:auto;height:300px;'><table class='new_silver_table' id='retainchannelTableX' ><thead><tr><th onclick=\" tableSorting('retainchannelTable', 1); \"  id='retainchannelTableth1' >首次使用时间</th><th>新用户</th><th>留存率</th></tr></thead>"
                
               
                g_table = ""
                rtable = u"\"日期\",\"推广渠道\",\"客户端产品\",\"新增下载数\",\"总下载数\"\n"
                atable = u"\"日期\";\"推广渠道\";\"客户端产品\";\"新增下载数\";\"总下载数\"\n"
                
                if date_type == "day":
                    sql = " SELECT a.total_download_add,b.name,b.mark_id,a.date,a.app_id,a.total_download_num,b.url FROM `stat_oper_board` a left join stat_oper_dict b on a.app_id = b.id where a.date >= %s and a.date < %s   group by a.date,a.app_id " % (st_datestr,et_datestr)
                else:
                    sql = " SELECT a.total_download_add,b.name,b.mark_id,a.date,a.app_id,a.total_download_num,b.url FROM `stat_oper_board_month` a left join stat_oper_dict b on a.app_id = b.id where a.start_date >= %s and a.end_date < %s   group by a.date,a.app_id " % (st_datestr,et_datestr)
                print sql
                c.execute(sql)  
                result_teall = c.fetchall()
                
                
                result_teall_table = []
                for ich in result_teall[::-1]:
                    result_teall_table.append(ich)
                
                #生成excel
                for x in result_teall_table:
                    _date = int(x[3])
                    _num = int(x[0])
                    _num_all = int(x[5])
                    _url = str(x[6])
                    _name = str(x[1])
                    _mark_id = str(x[2])
                    
                    if _mark_id == "1":
                        mark_name = "安卓市场"
                    elif _mark_id == "2":
                        mark_name = "安智市场"
                    elif _mark_id == "3":
                        mark_name = "91助手"
                    elif _mark_id == "4":
                        mark_name = "应用汇"
                    elif _mark_id == "5":
                        mark_name = "优亿市场"
                    elif _mark_id == "6":
                        mark_name = "机锋市场"
                    elif _mark_id == "7":
                        mark_name = "3g市场"
                        
                    if _mark_id in mark_item:
                        rtable += "\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"\n" % (_date,mark_name,_name,_num,_num_all)
                    
                    if _mark_id in mark_item:
                        atable += "\"%s\";\"%s\";\"%s\";\"%s\";\"%s\"\n" % (_date,mark_name,_name,_num,_num_all)
                
                
                days = []
                for x in result_teall:
                    _date = int(x[3])
                    if _date not in days:
                        days.append(_date)
                        
                days_table = []
                for ich in days[::-1]:
                    days_table.append(ich)
                
                #生成表格
                jishu = 1
                for day in days_table:
                    
                    bg = ""
                    if jishu % 2 == 0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                    
                    #print jishu % 2
                            
                            
                    
                    
                    
                    for mark_i in mark_item:
                        
                        
                        
                        
                        if mark_i == "1":
                            mark_name = "安卓市场"
                        elif mark_i == "2":
                            mark_name = "安智市场"
                        elif mark_i == "3":
                            mark_name = "91助手"
                        elif mark_i == "4":
                            mark_name = "应用汇"
                        elif mark_i == "5":
                            mark_name = "优亿市场"
                        elif mark_i == "6":
                            mark_name = "机锋市场"
                        elif _mark_id == "7":
                            mark_name = "3g市场"
                        
                        '''
                        if mark_i == "3":
                            g_table += "<tr  %s ><td style='text-align:center;padding:0px;'><div style='margin-top:100px;'>%s</div></td><td style='text-align:center;'>%s</td>" % (bg,day,mark_name)
                        '''
                        if mark_i == "6":
                            g_table += "<tr style='border-bottom:1px solid #D8D7D7'  %s ><td style='text-align:center;padding:0px'>%s</td><td style='text-align:center;padding:0px'>%s</td>" % (bg,day,mark_name)
                        else:
                            g_table += "<tr style='border-bottom:1px solid #D8D7D7'  %s ><td style='text-align:center;'>%s</td><td style='text-align:center;'>%s</td>" % (bg,day,mark_name)
                        
                        
                        now_box = []
                        for x in result_teall:
                            _date = int(x[3])
                            _num = int(x[0])
                            _num_all = int(x[5])
                            _url = str(x[6])
                            _name = str(x[1])
                            _mark_id = str(x[2])
                            
                            keybb = {}
                            keybb['num'] = _num
                            keybb['num_all'] = _num_all
                            keybb['name'] = _name
                            keybb['url'] = _url
                            
                            if _mark_id == mark_i and _date == day:
                                now_box.append(keybb)
                        
                        g_table += "<td style='text-align:center;padding:0px;'><table style='border-left:0px;border-bottom:0px;border-right:0px;border-top:0px;border-collapse: separate;' class='protetable'  >" 
                        try:
                            for client_i in client_item:
                                #print client_item
                                if client_i == "1":
                                    dd = 0
                                elif client_i == "2":
                                    dd = 1
                                elif client_i == "3":
                                    dd = 2
                                elif client_i == "4":
                                    dd = 3
                                elif client_i == "5":
                                    dd = 4
                                g_table += "<tr  ><td style ='border-top:0px;border-left:0px;border-right:0px;border-bottom:1px solid #D8D7D7;text-align:center;' ><a target='_blank' href = '%s'>%s</a></td></tr>" % (str(now_box[dd]['url']),str(now_box[dd]['name']))
                        except:
                            pass
                        g_table += "</table></td>"
                        
                        g_table += "<td style='text-align:center;padding:0px;'><table  style='border-left:0px;border-bottom:0px;border-right:0px;border-top:0px;border-collapse: separate;' class='protetable' >" 
                        try:
                            for client_i in client_item:
                                if client_i == "1":
                                    dd = 0
                                elif client_i == "2":
                                    dd = 1
                                elif client_i == "3":
                                    dd = 2
                                elif client_i == "4":
                                    dd = 3
                                elif client_i == "5":
                                    dd = 4
                                g_table += "<tr ><td style ='border-top:0px;border-left:0px;border-right:0px;border-bottom:1px solid #D8D7D7;text-align:center;' >%s</td></tr>" % cnsort.num2money(int(now_box[dd]['num']))
                        except:
                            pass
                        g_table += "</table></td>"
                        
                        
                        g_table += "<td style='text-align:center;padding:0px;'><table style='border-left:0px;border-bottom:0px;border-right:0px;border-top:0px;border-collapse: separate;' class='protetable' >" 
                        try:
                            for client_i in client_item:
                                if client_i == "1":
                                    dd = 0
                                elif client_i == "2":
                                    dd = 1
                                elif client_i == "3":
                                    dd = 2
                                elif client_i == "4":
                                    dd = 3
                                elif client_i == "5":
                                    dd = 4
                                g_table += "<tr ><td style ='border-top:0px;border-left:0px;border-right:0px;border-bottom:1px solid #D8D7D7;text-align:center;' >%s</td></tr>" % cnsort.num2money(int(now_box[dd]['num_all']))
                        except:
                            pass
                        g_table += "</table></td>"
                        
                    
                        g_table+="</tr>"
                    
                    
                        
                    jishu = jishu + 1
                g_table+="</table></div>"
                
                
                #生成线性图
                if date_type == "day":
                    xianx = "["
                    for xy in days:
                        xy = str(xy)
                        yy = xy[0:4]
                        mm = xy[4:6]
                        dd = xy[6:]
                        xianx += "'%s/%s/%s'," % (yy,mm,dd)
                    xianx = xianx.rstrip(",")
                    xianx += "]"
                else:
                    xianx = "["
                    for xy in days:
                        xy = str(xy)
                        xianx += "'%s'," % xy
                    xianx = xianx.rstrip(",")
                    xianx += "]"
                
                 
                jilu_it = []
                for x in result_teall:
                    _date = int(x[3])
                    _app_id = str(x[4])
                    _name_en = str(x[5])
                    _num = int(x[0])
                    _name = str(x[1])
                    _mark_id = str(x[2])

                    fs = {}
                    fs['num'] = _num
                    fs['date'] = _date
                    fs['app_id'] = _app_id
                    fs['name'] = _name
                    fs['mark_id'] = _mark_id
                    jilu_it.append(fs)
                
                _items_xian = []
                sql = " select distinct(name) from stat_oper_dict "
                c.execute(sql)  
                result = c.fetchall()
                xianm = "["
                for y in result:
                    _items_xian.append(str(y[0]))
                    xianm += "'%s'," % str(y[0])
                xianm = xianm.rstrip(",")
                xianm += "]"
                
                xiany = {}
                
                for mark_i in mark_item:
                
                    xianlin = "["
                    for xc in _items_xian:
                        xianstr = ""
                        for cs in jilu_it:
                            for day in days:
                                #print xc
                                if cs['name'] == xc and cs['date'] == day and cs['mark_id'] == mark_i:
                                    xianstr += "%s," % cs['num']
                        xianstr = xianstr.rstrip(",")
                        xianlin += "[%s]," % xianstr
                    xianlin = xianlin.rstrip(",")
                    xianlin += "]"
                
                    xiany[str(mark_i)] = xianlin
                
                
                
                fv = {}
                
                fv['table'] = g_table
                fv['xianx'] = xianx
                fv['xiany'] = xiany
                fv['xianm'] = xianm
                fv['rtable'] = rtable
                fv['atable'] = atable
                
                
                if len(result_teall) > 0:
                    fanhui['zongji'] = "1"
                
                fanhui[xunhuan[vxunhuan]['name']] = fv
            
            c.close()
            db.close()
            _url = hashlib.md5(_url)
            _url.digest()
            try:
                mc.set(key=_url.hexdigest(), val=fanhui, min_compress_len=1024*1024)
            except Exception,e:
                print e
                pass
        else:
            fanhui = m_value
            
        self.write(fanhui)
        self.finish()


class ChannelDay(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        
        
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        m_value = mc.get(_md5.hexdigest()) or {}
        if settings.cache_on == 0:
            m_value = {}
        
        if not m_value:
        
        
            
            
            
            try:
                st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                return
            
            if not _pd:
                ed_time = datetime.datetime.now()
                delta = ed_time - st_time 
                _pd =  abs(delta.days)
            
            _pd = int(_pd)
            et_time = st_time + datetime.timedelta(days=_pd)
            st_datestr = st_time.strftime('%Y%m%d')
            et_datestr = et_time.strftime('%Y%m%d')
            
            all_data = []
            results = {}
            os_data = []
            
            days = []
            
            for i in xrange(0,_pd):
                now = datetime.datetime.strptime(st_datestr,'%Y%m%d')
                delta = datetime.timedelta(days=i)  
                n_days = now + delta  
                days.append(n_days.strftime('%Y%m%d'))
            
            
            if _osid == "":
                xunhuan = [{'name':'All','id':'-1'},{'name':'Android','id':'61'},{'name':'iOS','id':'52'},{'name':'WP7','id':'59'}]
            elif _device_type == "":
                xunhuan = [{'name':'All','id':'-1'},{'name':'Phone','id':'1'},{'name':'Pad','id':'2'}]
            else:
                xunhuan = [{'name':'All'}]
            
            db = connectMySQL.connMySQL_stat()
            c=db.cursor()
            
            days_c = []
            c.execute(" select date from result_channel where date >= %s and date < %s group by date " % (st_datestr,et_datestr) )  
            date_teall = c.fetchall()
            for xcx in date_teall:
                days_c.append(xcx[0]) 
            
            
            fanhui = {}
            fanhui['zongji'] = "0"
                        
            for vxunhuan in xrange(len(xunhuan)):
                #print xunhuan[vxunhuan]['id']
                
                g_table = u"<div style='overflow:auto;height:200px;'><table class='new_silver_table' id='channeldayTableX' ><thead><tr><th onclick=\" tableSorting('channeldayTable', 1); \"  id='channeldayTableth1' >序号</th><th>频道</th><th>播放量</th><th>占比</th></tr></thead>"
                
                if _osid == "":
                    if _osid == "" and _device_type == "":
                        sql = "SELECT `channel`,date,sum(vv) FROM `result_channel` WHERE date >= %s and date < %s  and os_id = '%s' and device_type = '-1' group by channel order by sum(vv) desc " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'])
                    else:
                        sql = "SELECT `channel`,date,sum(vv) FROM `result_channel` WHERE date >= %s and date < %s  and os_id = '%s' and device_type = '%s' group by channel order by sum(vv) desc " % (st_datestr,et_datestr,xunhuan[vxunhuan]['id'],_device_type)
                elif _device_type == "":
                    sql = "SELECT `channel`,date,sum(vv) FROM `result_channel` WHERE date >= %s and date < %s  and os_id = '%s' and device_type = '%s' group by channel order by sum(vv) desc " % (st_datestr,et_datestr,_osid,xunhuan[vxunhuan]['id'])
            
                else:
                    sql = "SELECT `channel`,date,sum(vv) FROM `result_channel` WHERE date >= %s and date < %s  and os_id = '%s' and device_type = '%s' group by channel order by sum(vv) desc " % (st_datestr,et_datestr,_osid,_device_type)
              
                print sql
                c.execute(sql)  
                result_teall = c.fetchall()
                
                bingtu = ""
                qitashu = 0
                bingtujishu = 0
                zongvv_list = []
                
                
                for x in result_teall:
                    zongvv_list.append(x[2])
                
                zongvv = sum(zongvv_list)
                #days_c = list(set(days_c))
                
                zongjieheji = []
                
                jishu = 1
                for x in result_teall:
                    bg = ""
                    if jishu % 2 == 0:
                        bg = " class='new_silver_even' "
                    else:
                        bg = " class='new_silver_odd' "
                    
                    xianvv = x[2]
                    
                    try:
                        a = xianvv/zongvv
                    except:
                        a = 0
                        
                    zhanbi = round(a,4)
                    nl = str(zhanbi).split(".")
                    if len(str(nl[1])) < 4:
                        g_table += "<tr %s ><td>%s</td><td>%s</td><td>%s</td><td>%s0%%</td></tr>" % (bg,jishu,x[0],cnsort.num2money(x[2]),(zhanbi)*100)
                    else:
                        g_table += "<tr %s ><td>%s</td><td>%s</td><td>%s</td><td>%s%%</td></tr>" % (bg,jishu,x[0],cnsort.num2money(x[2]),(zhanbi)*100)
                    
                    
                    zongjieheji.append(x[2])
                    if bingtujishu <= 8:
                        bingtu += "['%s',%s]," % (x[0],x[2])
                    else:
                        qitashu += x[2]
                    jishu = jishu + 1
                    bingtujishu = bingtujishu + 1
                g_table+="</table></div>"
                bingtu += u"['OTHER',%s]," % qitashu 
                bingtu = "[%s]" % bingtu
                zongjieheji_sum = sum(zongjieheji)
                
                #明细表开始
                m_table = u"<div class=\"csv-box-header\"><strong>明细</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('channeldayTableX1');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('channeldayTableX1');\" >下载</a></span><a href=\"javascript:getCSVData('channeldayTableX');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>";
                    
                m_table += u"<div style='overflow:auto;height:300px;' class='bgbg'><table class='new_silver_table' id='channeldayTableX1'  ><thead><tr><th onclick=\" tableSortingly('channeldayTable', 1,1); \"  id='channeldayTableth1'  >日期</th><th>当日合计</th>"
                
                for x in result_teall:
                    m_table += "<th>%s</th>" % x[0]
                m_table += "</tr></thead>"
                
                days_l = []
                for days_cc in days_c:
                    
                    if _osid == "":
                        if _osid == "" and _device_type == "":
                            sql = "SELECT `channel`,date,sum(vv) FROM `result_channel` WHERE date = %s  and os_id = '%s' and device_type = '-1' group by channel  " % (days_cc,xunhuan[vxunhuan]['id'])
                            
                        else:
                            sql = "SELECT `channel`,date,sum(vv) FROM `result_channel` WHERE date = %s  and os_id = '%s' and device_type = '%s' group by channel  " % (days_cc,xunhuan[vxunhuan]['id'],_device_type)
                        
                    elif _device_type == "":
                        sql = "SELECT `channel`,date,sum(vv) FROM `result_channel` WHERE date = %s  and os_id = '%s' and device_type = '%s' group by channel  " % (days_cc,_osid,xunhuan[vxunhuan]['id'])
                
                    else:
                        sql = "SELECT `channel`,date,sum(vv) FROM `result_channel` WHERE date = %s  and os_id = '%s' and device_type = '%s' group by channel  " % (days_cc,_osid,_device_type)
                    
                    #print sql
                    c.execute(sql)  
                    hang_all = c.fetchall()
                    days_x = {}
                    for x in hang_all:
                        days_x[x[0]] = x[2]
                    
                    days_l.append(days_x)
                    
                #print 1234,days_l[0]
                #print days_c
                
                jishuc = 1
                for xy in xrange(len(days_c)):
                    
                    
                    
                    if jishuc % 2 ==0:
                        jishucbg = " class='new_silver_even' "
                    else:
                        jishucbg = " class='new_silver_odd' "
                    
                    #print 'kk',days_c[xy]
                    m_table += "<tr %s><td>%s(%s)</td>" % (jishucbg,cnsort.fordate(str(days_c[xy]),3),common.getxingqi(str(days_c[xy])))
                        
                   
                    m_table_channel = ""
                        
                    jizonghe = 0
                    jizonghelastday = 0
                        
                    for x in result_teall:
                        
                        """
                        lastday = str5.get(x[1])
                        nowday = str3.get(x[1])
                        cha = nowday - lastday
                            
                        if cha > 0:
                            jiantou = "<span class='inc_tag' style='margin-left: 5px;' title='0%'><b> ↑ </b></span>"
                        elif cha < 0:
                            jiantou = "<span class='des_tag' style='margin-left: 5px;' title='0%'><b> ↓ </b></span>"
                        else:
                            jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
                            
                            
                        if xy == 0:
                            jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
                        """
                        key = x[0]
                        m_table_channel += "<td>%s</td>" % cnsort.num2money(days_l[xy][key])
                        jizonghe += days_l[xy][key]
                        
                    """
                    lastday = jizonghelastday
                    nowday = jizonghe
                    cha = nowday - lastday
                            
                    if cha > 0:
                        jiantou = "<span class='inc_tag' style='margin-left: 5px;' title='0%'><b> ↑ </b></span>"
                    elif cha < 0:
                        jiantou = "<span class='des_tag' style='margin-left: 5px;' title='0%'><b> ↓ </b></span>"
                    else:
                        jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
                            
                            
                    if xy == 0:
                        jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
                    """
                        
                    m_table += "<td>%s</td>" % cnsort.num2money(jizonghe)
                        
                    m_table += m_table_channel
                        
                    m_table += "</tr>"
                
                    jishuc = jishuc + 1
                
                
                m_table += u"<tr><th class='new_silver_first_n footer'>总计</th><th style=\"text-align:right;\" class=\"footer\">%s</th>" % cnsort.num2money(zongjieheji_sum)
                
                for cc in zongjieheji:
                    m_table += "<th style=\"text-align:right;\" class=\"footer\">%s</th>" % cnsort.num2money(cc)
                
                m_table += "</tr>"
                
                m_table+="</table></div>"
                  
                
                
                zong_table = "%s%s" % (g_table,m_table)
                
                
                fv = {}
                
                fv['table'] = zong_table
                fv['bingtu'] = bingtu
                
                if len(result_teall) > 0:
                    fanhui['zongji'] = "1"
                
                fanhui[xunhuan[vxunhuan]['name']] = fv
            
            c.close()
            db.close()
            _url = hashlib.md5(_url)
            _url.digest()
            try:
                mc.set(key=_url.hexdigest(), val=fanhui, min_compress_len=1024*1024)
            except Exception,e:
                print e
                pass
        else:
            fanhui = m_value
            
        self.write(fanhui)
        self.finish()




class ChannelDay_copy(BaseHandler):
    def get(self): 
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        _osid = self.get_argument('os','').strip()
        _device_type = self.get_argument('dt','').strip()
        
        _order = " "
        _whereos = " os_id in (61,59,52) "
        _wheredy = "  "
        
        if _osid != "":
            _whereos = " os_id = %s " % _osid
        
        if _device_type != "":
            _wheredy = " and device_type in (%s) " % _device_type
        
        try:
            st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
        except :
            self.send_error(400, desc='invalid argument')
            return
        
        if not _pd:
            ed_time = datetime.datetime.now()
            delta = ed_time - st_time 
            _pd =  abs(delta.days)
        
        _pd = int(_pd)
        et_time = st_time + datetime.timedelta(days=_pd)
        st_datestr = st_time.strftime('%Y%m%d')
        et_datestr = et_time.strftime('%Y%m%d')
        
        all_data = []
        results = {}
        os_data = []
        
        days = []
        days_l = []
        
        for i in xrange(0,_pd):
            now = datetime.datetime.strptime(st_datestr,'%Y%m%d')
            delta = datetime.timedelta(days=i)  
            n_days = now + delta  
            days.append(n_days.strftime('%Y%m%d'))
            days_l.append({'days':n_days.strftime('%Y%m%d')})
        
        
        if _osid == "":
            xunhuan = [{'name':'All','id':'61,59,52'},{'name':'Android','id':'61'},{'name':'iOS','id':'52'},{'name':'WP7','id':'59'}]
            _where = " and device_type in (%s) " % _device_type
        elif _device_type == "":
            xunhuan = [{'name':'All','id':'1,2'},{'name':'Phone','id':'1'},{'name':'Pad','id':'2'}]
            _where = " and os_id in (%s) " % _osid
        else:
            xunhuan = [{'name':'All'}]
            _where = " and os_id in (%s) and device_type in (%s) " % (_osid,_device_type)
        
        db = connectMySQL.connMySQL_stat()
        c=db.cursor()
        
        
        json_fix = []
        sql = " SELECT vv_json FROM `channel_day_vv` where vv_json != '{}' and partner_mode in (1,2,3,8)  "
        c.execute(sql)  
        resjson = c.fetchall()
        for vl in resjson:
            strc = str(vl[0])
            arr0 = json.loads(strc)
            for key,value in arr0.items():
                json_fix.append(key)
        json_fix = set(json_fix)
        
        fanhui = {}
        for vxunhuan in xrange(len(xunhuan)):
        
            zongvv_list = []
            keylist = []
            g_table = u"<div style='overflow:auto;height:100px;'><table class='new_silver_table' id='channeldayTableX' ><thead><tr><th onclick=\" tableSorting('channeldayTable', 1); \"  id='channeldayTableth1' >序号</th><th>频道</th><th>播放次数</th><th>占比</th></tr></thead>"
            str3 = {}
            
            
            for xy in days:
            
                
                if _osid == "":
                    if _osid == "" and _device_type == "":
                        sql = "SELECT date,os_id,device_type,vv_json FROM `channel_day_vv` WHERE date = '%s'  and vv_json != '{}' and  business_type = 2 and pid_stat = 1 and os_id in (%s) and device_type in (1,2) and partner_mode in (1,2,3,8) " % (xy,xunhuan[vxunhuan]['id'])
                    else:
                        sql = "SELECT date,os_id,device_type,vv_json FROM `channel_day_vv` WHERE date = '%s'  and vv_json != '{}' and  business_type = 2 and pid_stat = 1 and os_id in (%s) and device_type in (%s) and partner_mode in (1,2,3,8) " % (xy,xunhuan[vxunhuan]['id'],_device_type)
                elif _device_type == "":
                    sql = "SELECT date,os_id,device_type,vv_json FROM `channel_day_vv` WHERE date = '%s'  and vv_json != '{}' and  business_type = 2 and pid_stat = 1 and os_id in (%s) and device_type in (%s) and partner_mode in (1,2,3,8) " % (xy,_osid,xunhuan[vxunhuan]['id'])
                else:
                    sql = "SELECT date,os_id,device_type,vv_json FROM `channel_day_vv` WHERE date = '%s'  and vv_json != '{}' and  business_type = 2 and pid_stat = 1 and os_id in (%s) and device_type in (%s) and partner_mode in (1,2,3,8) " % (xy,_osid,_device_type)
                
                
                #logging.info(sql)
                c.execute(sql)  
                res = c.fetchall()
                if res:
                    
                    for y in res:
                        date = str(y[0])
                        os = int(y[1])
                        device_type = int(y[2])
                        vv_json = str(y[3])
                        arr0 = json.loads(vv_json)
                        vv = arr0.keys()
                        
                        for ssc in json_fix:
                            if ssc not in vv:
                                arr0[ssc] = 0
                        
                        for key,value in arr0.items():
                            str3[key] = str3.get(key,0) + value
            
                else:
                    pass
            
            zongjieheji = [] 
            danjieheji = []
            print str3
            for key,value in str3.items():
                keylist.append([value,key])
                zongvv_list.append(value)
            keylist = sorted(keylist,reverse=True)
            
            zongvv = sum(zongvv_list)
                    
            jishu = 1
            bingtujishu = 0
            bingtu = ""
            qitashu = 0
            
            #print keylist
            
            for x in keylist:
                bg = ""
                if jishu % 2 == 0:
                    bg = " class='new_silver_even' "
                else:
                    bg = " class='new_silver_odd' "
                xianvv = str3.get(x[1])
                a = xianvv/zongvv
                zhanbi = round(a,4)*100
                g_table += "<tr %s ><td>%s</td><td>%s</td><td>%s</td><td>%s%%</td></tr>" % (bg,jishu,x[1],cnsort.num2money(str3.get(x[1])),zhanbi)
                zongjieheji.append(str3.get(x[1]))
                
                if bingtujishu <= 9:
                    bingtu += "['%s',%s]," % (x[1],str3.get(x[1]))
                else:
                    qitashu += str3.get(x[1])
                
                jishu = jishu + 1
                bingtujishu = bingtujishu + 1
                    
            g_table+="</table></div>"
            bingtu += u"['其他',%s]," % qitashu 
            bingtu = "[%s]" % bingtu
            zongjieheji_sum = sum(zongjieheji)
            
            
            m_table = u"<div class=\"csv-box-header\"><strong>明细</strong><div class=\"mnum\" style=\"color:#444\"><span><span style=\"display:none;\"><input onclick=\"getCSVData_save('channeldayTableX1');\" type=\"button\"  id=\"createcsv\" value=\"生成csv\" /></span><a href=\"javascript:getCSVData('channeldayTableX1');\" >下载</a></span><a href=\"javascript:getCSVData('channeldayTableX');\"><img src=\"resources/images/csv.png\" style=\"vertical-align: middle;\" \></a></div></div>";
                
            m_table += u"<div style='overflow:auto;height:500px;'><table class='new_silver_table' id='channeldayTableX1'  ><thead><tr><th onclick=\" tableSortingly('channeldayTable', 1,1); \"  id='channeldayTableth1'  >日期</th><th>当日合计</th>"
            
            for x in keylist:
                m_table += "<th>%s</th>" % x[1]
            m_table += "</tr></thead>"
            jishuc = 1
            
            
            for xy in xrange(len(days_l)):
                
                
                if _osid == "":
                    
                    if _osid == "" and _device_type == "":
                        sql = "SELECT date,os_id,device_type,vv_json FROM `channel_day_vv` WHERE date = '%s'  and vv_json != '{}' and  business_type = 2 and pid_stat = 1 and os_id in (%s) and device_type in (1,2) and partner_mode in (1,2,3,8) " % (days_l[xy]['days'],xunhuan[vxunhuan]['id'])
                    else:
                        sql = "SELECT date,os_id,device_type,vv_json FROM `channel_day_vv` WHERE date = '%s'  and vv_json != '{}' and  business_type = 2 and pid_stat = 1 and os_id in (%s) and device_type in (%s) and partner_mode in (1,2,3,8) " % (days_l[xy]['days'],xunhuan[vxunhuan]['id'],_device_type)
                    
                    
                elif _device_type == "":
                    sql = "SELECT date,os_id,device_type,vv_json FROM `channel_day_vv` WHERE date = '%s'  and vv_json != '{}' and  business_type = 2 and pid_stat = 1 and os_id in (%s) and device_type in (%s) and partner_mode in (1,2,3,8) " % (days_l[xy]['days'],_osid,xunhuan[vxunhuan]['id'])
                else:
                    sql = "SELECT date,os_id,device_type,vv_json FROM `channel_day_vv` WHERE date = '%s'  and vv_json != '{}' and  business_type = 2 and pid_stat = 1 and os_id in (%s) and device_type in (%s) and partner_mode in (1,2,3,8) " % (days_l[xy]['days'],_osid,_device_type)
                
                
                #logging.info(sql)
                c.execute(sql)  
                res = c.fetchall()
                str3 = {}
                if res:
                    for y in res:
                        date = str(y[0])
                        os = int(y[1])
                        device_type = int(y[2])
                        vv_json = str(y[3])
                        arr0 = json.loads(vv_json)
                        vv = arr0.keys()
                        
                        for ssc in json_fix:
                            if ssc not in vv:
                                arr0[ssc] = 0
                        
                        for key,value in arr0.items():
                            str3[key] = str3.get(key,0) + value
                else:
                    
                    for cy in keylist:
                        str3[cy[1]] = 0    
                
                days_l[xy]['cc'] = str3 
            
                      
            for xy in xrange(len(days_l)):
                
                str3 = days_l[xy]['cc']
                str5 = days_l[xy-1]['cc']
                
                if jishuc % 2 ==0:
                    jishucbg = " class='new_silver_even' "
                else:
                    jishucbg = " class='new_silver_odd' "
                
                m_table += "<tr %s><td>%s</td>" % (jishucbg,days_l[xy]['days'])
                    
                m_table_channel = ""
                    
                jizonghe = 0
                jizonghelastday = 0
                    
                for x in keylist:
                        
                    lastday = str5.get(x[1])
                    nowday = str3.get(x[1])
                    cha = nowday - lastday
                        
                    if cha > 0:
                        jiantou = "<span class='inc_tag' style='margin-left: 5px;' title='0%'><b> ↑ </b></span>"
                    elif cha < 0:
                        jiantou = "<span class='des_tag' style='margin-left: 5px;' title='0%'><b> ↓ </b></span>"
                    else:
                        jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
                        
                        
                    if xy == 0:
                        jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
                        
                    m_table_channel += "<td>%s%s</td>" % (cnsort.num2money(str3.get(x[1])),jiantou)
                    jizonghe += str3.get(x[1])
                    jizonghelastday += str5.get(x[1])
                    
                    
                lastday = jizonghelastday
                nowday = jizonghe
                cha = nowday - lastday
                        
                if cha > 0:
                    jiantou = "<span class='inc_tag' style='margin-left: 5px;' title='0%'><b> ↑ </b></span>"
                elif cha < 0:
                    jiantou = "<span class='des_tag' style='margin-left: 5px;' title='0%'><b> ↓ </b></span>"
                else:
                    jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
                        
                        
                if xy == 0:
                    jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
                    
                m_table += "<td>%s%s</td>" % (cnsort.num2money(jizonghe),jiantou)
                    
                m_table += m_table_channel
                    
                m_table += "</tr>"
            
                jishuc = jishuc + 1
            
            
            m_table += u"<tr><th class='footer'>总计</th><th class='footer'>%s</th>" % cnsort.num2money(zongjieheji_sum)
            
            for cc in zongjieheji:
                m_table += "<th class='footer'>%s</th>" % cnsort.num2money(cc)
            
            m_table += "</tr>"
              
            m_table+="</table></div>"
              
            
            
            zong_table = "%s%s" % (g_table,m_table)
            
            
            fv = {}
            
            fv['table'] = zong_table
            fv['bingtu'] = bingtu
            
            fanhui[xunhuan[vxunhuan]['name']] = fv
        
        c.close()
        db.close()
        self.write(fanhui)
        self.finish()        
        

class Test(BaseHandler):
    
    
    
    def get(self):
        
        db = connectMySQL.connMySQL_stat()
        c=db.cursor()
        """
        sql = "SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server  FROM `stat_day_total` WHERE date>= 20120526 and date < 20120602 and business_type=2 and pid_stat=1 and os_id in (52,59,61) and partner_mode in (1,2,3,8) group by date,os_id "
        c.execute(sql)  
        res= c.fetchall()
        uvs = 0
        for x in res:
            date = str(x[0])
            pv = int(x[3])
            uv = int(x[4])
            uvs += uv
        
        print uvs
        
        fanhui = {}
        fanhui['hc'] = '4561'
        mc = cnsort.setmc()
        mc.set('20120627&20120703&mainclient', fanhui)
        zhi = mc.get('20120627&20120703&mainclient') or {}
        
        if not zhi:
            ss = "no"
        else:
            ss = "yes"
        """
        import httplib2
        http = httplib2.Http()
        headers = {'Cookie':cookie_value}
        
        self.write(headers)
        self.finish()
        
        
class HelloWorld(BaseHandler):
    
    
    
    def get(self):
        
        
        
        
        self.write("hello world!")
        self.finish()
        
class WriteFile(BaseHandler):
    
    
    
    def get(self):
        
        _content = self.get_argument('content','').strip()
        file_object = open('test.txt','a')
        file_object.write(_content)
        file_object.close( )
        
        self.write(u"写入成功")
        self.finish()



class FnameCn(BaseHandler):
    
    
    
    def get(self):
        
        
        
        
        
        _btype = self.get_argument('type','video').strip()
        bt_sql = ""
    
        if _btype == "video":
            bt_sql = "2"
            fanhui = u"<select id=\"FactoryVideoFactory_cn\" onchange=\"changeFactoryVideoFactory(this);\"><option value='全部'>全部</option>"
        if _btype == "paike":
            bt_sql = "4"
            fanhui = "<select id=\"FactoryPaikeFactory_cn\" onchange=\"changeFactoryPaikeFactory(this);\"><option value=''>全部</option>"
        if _btype == "retainfactory":
            bt_sql = "2,4"
            fanhui = "<select id=\"retainfactoryf_id\" >"
            
        db = connectMySQL.connMySQL_mobileProduction()
        c=db.cursor()
        sql = "select distinct f.id as fid, f.name_cn as fname  from s_os as o, s_factory as f, (SELECT distinct f_id,   os_id,device_type FROM  `s_partner_new` WHERE  `partner_mode` =1 and pid_stat=1 and business_type in (%s) ) a where o.id = a.os_id and f.id = a.f_id and f_id != 3 " % bt_sql
        c.execute(sql)  
        res= c.fetchall()
        c.close()
        db.close()
        charts = []
        for x in res:
            fname = x[1]
            f_id = x[0]
            
            if fname.isalpha():
                fnamec = fname.capitalize()
            else:
                fnamec = fname.lower()
            
            pinyin = cnsort.multi_get_letter(fnamec)
            
            
            
            charts.append([pinyin,fname,f_id])
            
        rescs = sorted(charts)
        
        
        for ii in xrange(len(rescs)):
            #if rescs[ii][2] == 12:
            #    fanhui+="<option selected=selected value='%s'>%s</option>" % (rescs[ii][2],rescs[ii][1])
            #else:
            fanhui+="<option value='%s'>%s</option>" % (rescs[ii][2],rescs[ii][1])
        
        fanhui+="</select>"
        
        self.write(fanhui)
        self.finish()
        
        


class PnameCn(BaseHandler):
    
    
    
    def get(self):
        
        
        
        _btype = self.get_argument('type','video').strip()
        bt_sql = ""
    
        if _btype == "video":
            bt_sql = "2"
            fanhui = "<select  id=\"PromoVideoFactory_cn\" onchange=\"changePromoVideoFactory(this);\"><option value='全部'>全部</option>"
        if _btype == "paike":
            bt_sql = "4"
            fanhui = "<select  id=\"PromoPaikeFactory_cn\" onchange=\"changePromoPaikeFactory(this);\"><option value='全部'>全部</option>"
        if _btype == "retainchannel":
            bt_sql = "2,4"
            fanhui = "<select  id=\"retainchannelf_id\" >"
            
        _ftype = self.get_argument('ftype',"8").strip()
        
        if _ftype == "8":
            ft_sql = "  8 "
        if _ftype == "2":
            ft_sql = "  2 "
        
        
        
        
        db = connectMySQL.connMySQL_mobileProduction()
        c=db.cursor()
        sql = "select distinct f.id as fid, f.name_cn as fname  from s_os as o, s_factory as f, (SELECT distinct f_id,   os_id,device_type,partner_mode FROM  `s_partner_new` WHERE   pid_stat=1 and business_type in (%s) and partner_mode = %s ) a where o.id = a.os_id and f.id = a.f_id " % (bt_sql,ft_sql)
        print sql
        c.execute(sql)  
        res= c.fetchall()
        c.close()
        db.close()
        charts = []
        for x in res:
            fname = x[1]
            f_id = x[0]
            
            if fname.isalpha():
                fnamec = fname.capitalize()
            else:
                fnamec = fname.lower()
            
            pinyin = cnsort.multi_get_letter(fnamec)
            
            
            charts.append([pinyin,fname,f_id])
            
        rescs = sorted(charts)
        
        
        for ii in xrange(len(rescs)):
            if rescs[ii] != '':
                fanhui+="<option value='%s'>%s</option>" % (rescs[ii][2],rescs[ii][1])
        
        fanhui+="</select>"
        
        self.write(fanhui)
        self.finish()

        
           
        
    
    


        
        
class MajorVideoAnalytics(BaseHandler):
    def get(self): 
        openmix = 0
        table_name = "stat_day_total"
        os_json = clientcache.getOS()
        
        pidtype_json = clientcache.getPidType()
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        
        _dt = self.get_argument('dt','no').strip()
        _os_id = self.get_argument('os','no').strip()
        _pm = self.get_argument('pm','no').strip()
        _value = self.get_argument('value','no').strip()
        ossql = ""
        
        if (_os_id == "no") and (_dt == "no") and (_pm == "no") :
            ossql = "   "
        elif (_os_id != "no") and (_dt == "no") and (_pm == "no") :
            ossql = " ,device_type  "
        elif (_os_id == "no") and (_dt != "no") and (_pm == "no") :
            ossql = " ,device_type  "
        elif (_os_id == "no") and (_dt == "no") and (_pm != "no") :
            ossql = " ,partner_mode "
        elif (_os_id != "no") and (_dt != "no") and (_pm != "no") :
            ossql = " ,device_type,partner_mode  "
        elif (_os_id != "no") and (_dt != "no") and (_pm == "no") :
            ossql = " ,device_type,partner_mode  "                 
        elif (_os_id != "no") and (_dt == "no") and (_pm != "no") :
            ossql = " ,device_type,partner_mode  "
        elif (_os_id == "no") and (_dt != "no") and (_pm != "no") :
            ossql = " ,device_type,partner_mode  "
        
        try:
            st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
        except :
            self.send_error(400, desc='invalid argument')
            return
        
        if not _pd:
            ed_time = datetime.datetime.now()
            delta = ed_time - st_time 
            _pd =  abs(delta.days)
        
        _pd = int(_pd)
        et_time = st_time + datetime.timedelta(days=_pd)
        st_datestr = st_time.strftime('%Y%m%d')
        et_datestr = et_time.strftime('%Y%m%d')
        
        all_data = []
        results = {}
        os_data = []
        
        #connection = pymongo.Connection("10.103.13.42", 27017)
        #db = connection.DailyLog
        db = connectMySQL.connMySQL_stat()
        c=db.cursor()
        #sql = "SELECT date, os, type, pv, uv, vv  FROM `view_day_mainAnalytics` WHERE date>= '{0}' and date < '{1}'".format(st_datestr, et_datestr)
        #sql = "SELECT date, os_id, pid_type, pv, uv, vv  FROM `viewdaymain` WHERE date>= '{0}' and date < '{1}'".format(st_datestr, et_datestr)
        #if _os_id == "no":
        sql = "SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server  FROM `{0}` WHERE date>= {1} and date < {2} and business_type=2 and pid_stat=1 and os_id in (52,59,61) and partner_mode in (1,2,3,8) group by date,os_id {3} ".format(table_name,st_datestr,et_datestr,ossql)
        print sql
        logging.info(sql)
        c.execute(sql)  
        res= c.fetchall()
        #print len(res)
        _tmpdate = ''
        for x in res:
            date = str(x[0])
            os = os_json.get(int(x[1])) or 'null'
            #type1 = pidtype_json.get(int(x[2])) or 'null'
            if int(x[1]) != 72:
                type1 = settings.device_type.get(str(x[2])) or 'unkown'
            else :
                type1 = ''
            pv = int(x[3])
            uv = int(x[4])
            vv = int(x[5])
            nu = int(x[6])
            pm = int(x[7])
            before_duration = int(x[8])
            before_times = int(x[9])
            duration = int(x[10])
            complete = int(x[11])
            play_load_duration = int(x[12])
            play_load_times = int(x[13])
            play_hdsd_times = int(x[14])
            play_hdsd_duration = int(x[15])
            play_sdhd_times = int(x[16])
            play_sdhd_duration = int(x[17])
            
            if _tmpdate and _tmpdate != date:
                results['data'] = os_data
                results['year'] = _tmpdate[:4]
                results['month'] = _tmpdate[4:6]
                results['day'] = _tmpdate[6:]
                all_data.append(results)
                results = {}
                os_data = []
            if _value == "no":
                
                if _os_id == "ios":
                    _os_id = "iOS"
                    _os_id_sp = "52"
                if _os_id == "android":
                    _os_id = "Android"
                    _os_id_sp = "61"
                if _os_id == "wp7":
                    _os_id = "WP7"
                    _os_id_sp = "59"
                
                if _dt == "pad":
                    _dt = "Pad"
                if _dt == "phone":
                    _dt = "Phone"
                
                if _pm == "qudao":
                    _pm = 2
                if _pm == "changshang":
                    _pm = 1
                
                if pm == 8:
                    pm = 2
                
                pm_cn = ""
                if (pm == 1):
                    pm_cn = u"厂商内置"
                elif (pm == 2):
                    pm_cn = u"渠道推广"
                
                #print _tmpdate
                #以下是条件判断的设置    
                if os != 'FreeWap':
                    if (_os_id == "no") and (_dt == "no") and (_pm == "no") :
                        
                        play_resptime,play_times,draw_resptime,draw_times,getVideoDetail_resptime,getVideoDetail_times = clientcache.getJsondata(x[0],table_name,st_datestr,et_datestr,x[1],"no","no")
                        
                        os_data.insert(0,{'os':os, 'pv':pv, 'uv':uv, 'vv':vv, 'nu': nu,'before_duration' : before_duration,'before_times' : before_times,'duration' : duration,
            'complete' : complete,
            'play_load_duration' : play_load_duration,
            'play_load_times' : play_load_times,
            'play_hdsd_times' : play_hdsd_times,
            'play_hdsd_duration' : play_hdsd_duration,
            'play_sdhd_times' : play_sdhd_times,
            'play_sdhd_duration' : play_sdhd_duration,
            'play_resptime' : play_resptime,
        'play_times' : play_times,
        'draw_resptime' : draw_resptime,
        'draw_times' : draw_times,
        'getVideoDetail_resptime' : getVideoDetail_resptime,
        'getVideoDetail_times' : getVideoDetail_times,
            
            })
                    elif (_os_id != "no") and (_dt == "no") and (_pm == "no") :
                        if _os_id == os:
                            play_resptime,play_times,draw_resptime,draw_times,getVideoDetail_resptime,getVideoDetail_times = clientcache.getJsondata(x[0],table_name,st_datestr,et_datestr,x[1],x[2],"no")
                            os_data.insert(0,{'os_id':x[1],'os':os,'type':type1,'pv':pv, 'uv':uv, 'vv':vv, 'nu': nu,'before_duration' : before_duration,'before_times' : before_times,'duration' : duration,
            'complete' : complete,
            'play_load_duration' : play_load_duration,
            'play_load_times' : play_load_times,
            'play_hdsd_times' : play_hdsd_times,
            'play_hdsd_duration' : play_hdsd_duration,
            'play_sdhd_times' : play_sdhd_times,
            'play_sdhd_duration' : play_sdhd_duration,
           'play_times' : play_times,
           'play_resptime' : play_resptime,
        'draw_resptime' : draw_resptime,
        'draw_times' : draw_times,
        'getVideoDetail_resptime' : getVideoDetail_resptime,
        'getVideoDetail_times' : getVideoDetail_times,})
                    elif (_os_id == "no") and (_dt != "no") and (_pm == "no") :
                        
                        if _dt == type1:
                            play_resptime,play_times,draw_resptime,draw_times,getVideoDetail_resptime,getVideoDetail_times = clientcache.getJsondata(x[0],table_name,st_datestr,et_datestr,x[1],x[2],"no")
                            os_data.insert(0,{'os':os,'type':type1, 'pv':pv, 'uv':uv, 'vv':vv, 'nu': nu,'before_duration' : before_duration,'before_times' : before_times,'duration' : duration,
            'complete' : complete,
            'play_load_duration' : play_load_duration,
            'play_load_times' : play_load_times,
            'play_hdsd_times' : play_hdsd_times,
            'play_hdsd_duration' : play_hdsd_duration,
            'play_sdhd_times' : play_sdhd_times,
            'play_sdhd_duration' : play_sdhd_duration,
            'play_times' : play_times,
            'play_resptime' : play_resptime,
        'draw_resptime' : draw_resptime,
        'draw_times' : draw_times,
        'getVideoDetail_resptime' : getVideoDetail_resptime,
        'getVideoDetail_times' : getVideoDetail_times,})
                        
                    elif (_os_id == "no") and (_dt == "no") and (_pm != "no") :
                        if _pm == pm:
                            if _pm != 2:
                                play_resptime,play_times,draw_resptime,draw_times,getVideoDetail_resptime,getVideoDetail_times = clientcache.getJsondata(x[0],table_name,st_datestr,et_datestr,x[1],"no",pm)
                                os_data.insert(0,{'os':os,'pms':x[7],'pv':pv, 'uv':uv, 'vv':vv, 'nu': nu,'pm':pm_cn,'before_duration' : before_duration,'before_times' : before_times,'duration' : duration,
                'complete' : complete,
                'play_load_duration' : play_load_duration,
                'play_load_times' : play_load_times,
                'play_hdsd_times' : play_hdsd_times,
                'play_hdsd_duration' : play_hdsd_duration,
                'play_sdhd_times' : play_sdhd_times,
                'play_sdhd_duration' : play_sdhd_duration,
                'play_times' : play_times,
                'play_resptime' : play_resptime,
            'draw_resptime' : draw_resptime,
            'draw_times' : draw_times,
            'getVideoDetail_resptime' : getVideoDetail_resptime,
            'getVideoDetail_times' : getVideoDetail_times,})
                             
                            else:
                                _datetime = x[0]
                                strc = [{'name':'Android','id':'61'},{'name':'iOS','id':'52'},{'name':'WP7','id':'59'}]
                                for j in xrange(len(strc)):
                                    
                                    sql = "SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server FROM `%s` WHERE date = %s and business_type = 2 and pid_stat = 1 and partner_mode in (2,8) and os_id = %s " % (table_name,_datetime,strc[j]['id'])
                                    c.execute(sql)
                                    #print sql  
                                    _res = c.fetchone()
                                    _os_data_string = str(os_data)
                                    #print _res
                                    if _res[0] == None:
                                        if _os_data_string.find(strc[j]['name']) == -1:
                                            os_data.insert(0,{'os':strc[j]['name'],'pm':'渠道推广'})
                                    else:
                                        pv = int(_res[3])
                                        uv = int(_res[4])
                                        vv = int(_res[5])
                                        nu = int(_res[6])
                                        pm = int(_res[7])
                                        before_duration = int(_res[8])
                                        before_times = int(_res[9])
                                        duration = int(_res[10])
                                        complete = int(_res[11])
                                        play_load_duration = int(_res[12])
                                        play_load_times = int(_res[13])
                                        play_hdsd_times = int(_res[14])
                                        play_hdsd_duration = int(_res[15])
                                        play_sdhd_times = int(_res[16])
                                        play_sdhd_duration = int(_res[17])
                                        play_resptime,play_times,draw_resptime,draw_times,getVideoDetail_resptime,getVideoDetail_times = clientcache.getJsondata(_datetime,table_name,st_datestr,et_datestr,_res[1],"no",2)
                                        
                                        #_os_data_string = str(os_data)
                                        
                                        if _os_data_string.find(strc[j]['name']) == -1:
                                        
                                            os_data.insert(0,{'date':_datetime,'os':strc[j]['name'],'pms':_res[7],'pv':pv, 'uv':uv, 'vv':vv, 'nu': nu,'pm':pm_cn,'before_duration' : before_duration,'before_times' : before_times,'duration' : duration,'complete' : complete,'play_load_duration' : play_load_duration,'play_load_times' : play_load_times,'play_hdsd_times' : play_hdsd_times,'play_hdsd_duration' : play_hdsd_duration,'play_sdhd_times' : play_sdhd_times,'play_sdhd_duration' : play_sdhd_duration,'play_times' : play_times,'play_resptime' : play_resptime,'draw_resptime' : draw_resptime,'draw_times' : draw_times,'getVideoDetail_resptime' : getVideoDetail_resptime,'getVideoDetail_times' : getVideoDetail_times,})
                                    
                                    
                            
                            
                       
                    elif (_os_id != "no") and (_dt != "no") and (_pm != "no") :
                        
                        if _os_id == os and _dt == type1 and _pm == pm:
                            play_resptime,play_times,draw_resptime,draw_times,getVideoDetail_resptime,getVideoDetail_times = clientcache.getJsondata(x[0],table_name,st_datestr,et_datestr,x[1],x[2],pm)
                            if _pm == 2:
                                openmix = 1
                            
                            os_data.insert(0,{'os':os,'pms':x[7],'type':type1,'pv':pv, 'uv':uv, 'vv':vv, 'nu': nu,'pm':pm_cn,'before_duration': before_duration,'before_times' : before_times,'duration' : duration,
            'complete' : complete,
            'play_load_duration' : play_load_duration,
            'play_load_times' : play_load_times,
            'play_hdsd_times' : play_hdsd_times,
            'play_hdsd_duration' : play_hdsd_duration,
            'play_sdhd_times' : play_sdhd_times,
            'play_resptime' : play_resptime,
            'play_sdhd_duration' : play_sdhd_duration,
            'play_times' : play_times,
        'draw_resptime' : draw_resptime,
        'draw_times' : draw_times,
        'getVideoDetail_resptime' : getVideoDetail_resptime,
        'getVideoDetail_times' : getVideoDetail_times,})
                            
                       
                    elif (_os_id == "no") and (_dt != "no") and (_pm != "no") :
                        if _dt == type1 and _pm == pm:
                            play_resptime,play_times,draw_resptime,draw_times,getVideoDetail_resptime,getVideoDetail_times = clientcache.getJsondata(x[0],table_name,st_datestr,et_datestr,x[1],x[2],pm)    
                            os_data.insert(0,{'os':os,'type':type1, 'pv':pv, 'uv':uv, 'vv':vv, 'nu': nu,'pm':pm_cn,'before_duration' : before_duration,'before_times' : before_times,'duration' : duration,
            'complete' : complete,
            'play_load_duration' : play_load_duration,
            'play_load_times' : play_load_times,
            'play_hdsd_times' : play_hdsd_times,
            'play_hdsd_duration' : play_hdsd_duration,
            'play_sdhd_times' : play_sdhd_times,
            'play_sdhd_duration' : play_sdhd_duration,
            'play_times' : play_times,
            'play_resptime' : play_resptime,
        'draw_resptime' : draw_resptime,
        'draw_times' : draw_times,
        'getVideoDetail_resptime' : getVideoDetail_resptime,
        'getVideoDetail_times' : getVideoDetail_times,})
                                
                        
                    elif (_os_id != "no") and (_dt != "no") and (_pm == "no") :
                        if os == _os_id and type1 == _dt:
                            play_resptime,play_times,draw_resptime,draw_times,getVideoDetail_resptime,getVideoDetail_times = clientcache.getJsondata(x[0],table_name,st_datestr,et_datestr,x[1],x[2],"no")
                            openmix = 1
                            os_data.insert(0,{'pms':x[7],'os':os,'type':type1, 'pv':pv, 'uv':uv, 'vv':vv, 'nu': nu,'pm':pm_cn,'before_duration' : before_duration,'before_times' : before_times,'duration' : duration,
            'complete' : complete,
            'play_load_duration' : play_load_duration,
            'play_load_times' : play_load_times,
            'play_hdsd_times' : play_hdsd_times,
            'play_hdsd_duration' : play_hdsd_duration,
            'play_sdhd_times' : play_sdhd_times,
            'play_sdhd_duration' : play_sdhd_duration,
            'play_times' : play_times,
            'play_resptime' : play_resptime,
        'draw_resptime' : draw_resptime,
        'draw_times' : draw_times,
        'getVideoDetail_resptime' : getVideoDetail_resptime,
        'getVideoDetail_times' : getVideoDetail_times,})
                               
                    elif (_os_id != "no") and (_dt == "no") and (_pm != "no") :
                        if _os_id == os and _pm == pm:
                            play_resptime,play_times,draw_resptime,draw_times,getVideoDetail_resptime,getVideoDetail_times = clientcache.getJsondata(x[0],table_name,st_datestr,et_datestr,x[1],x[2],pm)
                            
                            
            
                            if _pm != 2:
                                os_data.insert(0,{'os':os,'pms':x[7],'type':type1,'pv':pv,'uv':uv, 'vv':vv, 'nu': nu,'pm':pm_cn,'before_duration' : before_duration,'before_times' : before_times,'duration' : duration,
                'complete' : complete,
                'play_load_duration' : play_load_duration,
                'play_load_times' : play_load_times,
                'play_hdsd_times' : play_hdsd_times,
                'play_hdsd_duration' : play_hdsd_duration,
                'play_sdhd_times' : play_sdhd_times,
                'play_sdhd_duration' : play_sdhd_duration,
                'play_times' : play_times,
                'play_resptime' : play_resptime,
            'draw_resptime' : draw_resptime,
            'draw_times' : draw_times,
            'getVideoDetail_resptime' : getVideoDetail_resptime,
            'getVideoDetail_times' : getVideoDetail_times,})
                         
                            
                            else:
                                _datetime = x[0]
                                strc = [{'name':'Phone','id':'1'},{'name':'Pad','id':'2'}]
                                for j in xrange(len(strc)):
                                    
                                    sql = "SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server FROM `%s` WHERE date = %s and business_type = 2 and pid_stat = 1 and partner_mode in (2,8) and device_type = %s and os_id = %s " % (table_name,_datetime,strc[j]['id'],_os_id_sp)
                                    c.execute(sql)
                                    print sql  
                                    _res = c.fetchone()
                                    print _res
                                    _os_data_string = str(os_data)
                                    if _res[0] == None:
                                        if _os_data_string.find(strc[j]['name']) == -1:
                                            os_data.insert(0,{'type':strc[j]['name'],'pm':'渠道推广'})
                                    else:
                                        pv = int(_res[3])
                                        uv = int(_res[4])
                                        vv = int(_res[5])
                                        nu = int(_res[6])
                                        pm = int(_res[7])
                                        before_duration = int(_res[8])
                                        before_times = int(_res[9])
                                        duration = int(_res[10])
                                        complete = int(_res[11])
                                        play_load_duration = int(_res[12])
                                        play_load_times = int(_res[13])
                                        play_hdsd_times = int(_res[14])
                                        play_hdsd_duration = int(_res[15])
                                        play_sdhd_times = int(_res[16])
                                        play_sdhd_duration = int(_res[17])
                                        play_resptime,play_times,draw_resptime,draw_times,getVideoDetail_resptime,getVideoDetail_times = clientcache.getJsondata(_datetime,table_name,st_datestr,et_datestr,_res[1],"no",2)
                                        
                                        
                                        
                                        if _os_data_string.find(strc[j]['name']) == -1:
                                        
                                            os_data.insert(0,{'date':_datetime,'type':strc[j]['name'],'pms':_res[7],'pv':pv, 'uv':uv, 'vv':vv, 'nu': nu,'pm':pm_cn,'before_duration' : before_duration,'before_times' : before_times,'duration' : duration,'complete' : complete,'play_load_duration' : play_load_duration,'play_load_times' : play_load_times,'play_hdsd_times' : play_hdsd_times,'play_hdsd_duration' : play_hdsd_duration,'play_sdhd_times' : play_sdhd_times,'play_sdhd_duration' : play_sdhd_duration,'play_times' : play_times,'play_resptime' : play_resptime,'draw_resptime' : draw_resptime,'draw_times' : draw_times,'getVideoDetail_resptime' : getVideoDetail_resptime,'getVideoDetail_times' : getVideoDetail_times,})     
                    
                    _tmpdate = date           
                        
            else:
                ss = "{"
                if _value.find('os') != -1:
                    ss += "'os':%s," % os
                if _value.find('type') != -1:
                    ss += "'type':%s," % type1
                if _value.find('pv') != -1:
                    ss += "'pv':%s," % pv
                if _value.find('uv') != -1:
                    ss += "'uv':%s," % uv
                if _value.find('vv') != -1:
                    ss += "'vv':%s," % vv
                if _value.find('nu') != -1:
                    ss += "'nu':%s," % nu
                ss += "}"
                os_data.insert(0,ss)  
                _tmpdate = date
        
        c.close()
        db.close()
        
        if len(os_data) > 0 :
            results['data'] = os_data
            results['year'] = _tmpdate[:4]
            results['month'] = _tmpdate[4:6]
            results['day'] = _tmpdate[6:]
            all_data.append(results)
            results = {}
            os_data = []
        
        all_data_copy = all_data
        
        
        
        
        
        
        
        
        if openmix == 1:
        
            pms2 = (2,8)
            for item_copy in all_data_copy:
                datas_copy = item_copy.get('data', [])
                tmp_data_copy = []
                del_index = []
                for i in range(len(datas_copy)):
                    if datas_copy[i].get('pms', 0) in pms2:
                        tmp_data_copy.append(datas_copy[i])
                        del_index.append(i)
                
                for i in range(len(del_index)):
                    if i == 0:
                        datas_copy.remove(datas_copy[del_index[i]])
                    else:
                        try:
                            datas_copy.remove(datas_copy[del_index[i] - 1])
                        except:
                            chekitout = 'chekitout'
                
                tmp_data_result = {}
                for tmp_data_json in tmp_data_copy:
                    for key,value in tmp_data_json.items():
                        
                        if key not in ('os', 'type', 'pm','pms') :
                            tmp_data_result[key] = tmp_data_result.get(key,0) + value
                        else:
                            if key == 'pm':
                                tmp_data_result['pm'] = value
                            if key == 'os':
                                tmp_data_result['os'] = value
                            if key == 'type':
                                tmp_data_result['type'] = value
                datas_copy.append(tmp_data_result)
            
        
        
        self.write({"status":"success", "items":all_data})
        self.finish()
        
class OldMajorVideoAnalytics(BaseHandler):
    def get(self): 
        table_name = "stat_day_total"
        os_json = clientcache.getOS()
        
        pidtype_json = clientcache.getPidType()
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        
        _dt = self.get_argument('dt','no').strip()
        _os_id = self.get_argument('os','no').strip()
        _pm = self.get_argument('pm','no').strip()
        _value = self.get_argument('value','no').strip()
        ossql = ""
        
        if (_os_id == "no") and (_dt == "no") and (_pm == "no") :
            ossql = "   "
        elif (_os_id != "no") and (_dt == "no") and (_pm == "no") :
            ossql = " ,device_type  "
        elif (_os_id == "no") and (_dt != "no") and (_pm == "no") :
            ossql = " ,device_type  "
        elif (_os_id == "no") and (_dt == "no") and (_pm != "no") :
            ossql = " ,partner_mode  "
        elif (_os_id != "no") and (_dt != "no") and (_pm != "no") :
            ossql = " ,device_type,partner_mode  "
        elif (_os_id != "no") and (_dt != "no") and (_pm == "no") :
            ossql = " ,device_type,partner_mode  "                 
        elif (_os_id != "no") and (_dt == "no") and (_pm != "no") :
            ossql = " ,device_type,partner_mode  "
        elif (_os_id == "no") and (_dt != "no") and (_pm != "no") :
            ossql = " ,device_type,partner_mode  "
        """
        ossql = ""
        if _os_id != "no":
            ossql = " device_type, "
        _dt = self.get_argument('dt','no').strip()
        dtsql = ""
        if _dt != "no":
            dtsql = " and (device_type = %s ) " % _dt
        _pm = self.get_argument('pm','no').strip()
        pmsql = ""
        if _pm != "no":
            pmsql = " and (partner_mode in (%s) ) " % _pm
        
        """
        
        try:
            st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
        except :
            self.send_error(400, desc='invalid argument')
            #self.write({"status": "failed", "code": 400,  "desc": "invalid argument"})
            #self.finish()
            return
        
        if not _pd:
            ed_time = datetime.datetime.now()
            delta = ed_time - st_time 
            _pd =  abs(delta.days)
        
        _pd = int(_pd)
        et_time = st_time + datetime.timedelta(days=_pd)
        st_datestr = st_time.strftime('%Y%m%d')
        et_datestr = et_time.strftime('%Y%m%d')
        
        all_data = []
        results = {}
        os_data = []
        
        #connection = pymongo.Connection("10.103.13.42", 27017)
        #db = connection.DailyLog
        db = connectMySQL.connMySQL_stat()
        c=db.cursor()
        #sql = "SELECT date, os, type, pv, uv, vv  FROM `view_day_mainAnalytics` WHERE date>= '{0}' and date < '{1}'".format(st_datestr, et_datestr)
        #sql = "SELECT date, os_id, pid_type, pv, uv, vv  FROM `viewdaymain` WHERE date>= '{0}' and date < '{1}'".format(st_datestr, et_datestr)
        sql = "SELECT date, os_id, device_type, sum(pv), sum(uv), sum(vv),sum(newuser),partner_mode,sum(before_duration),sum(before_times),sum(duration),sum(complete),sum(play_load_duration),sum(play_load_times),sum(play_hdsd_times),sum(play_hdsd_duration),sum(play_sdhd_times),sum(play_sdhd_duration),apiresp,server  FROM `{0}` WHERE date>= {1} and date < {2} and business_type=2 and pid_stat=1 and server != 'api3' group by date,os_id {3} ".format(table_name,st_datestr,et_datestr,ossql)
        print sql
        logging.info(sql)
        c.execute(sql)  
        res= c.fetchall()
        #print len(res)
        _tmpdate = ''
        for x in res:
            date = str(x[0])
            os = os_json.get(int(x[1])) or 'null'
            #type1 = pidtype_json.get(int(x[2])) or 'null'
            if int(x[1]) != 72:
                type1 = settings.device_type.get(str(x[2])) or 'unkown'
            else :
                type1 = ''
            pv = int(x[3])
            uv = int(x[4])
            vv = int(x[5])
            nu = int(x[6])
            pm = int(x[7])
            before_duration = int(x[8])
            before_times = int(x[9])
            duration = int(x[10])
            complete = int(x[11])
            play_load_duration = int(x[12])
            play_load_times = int(x[13])
            play_hdsd_times = int(x[14])
            play_hdsd_duration = int(x[15])
            play_sdhd_times = int(x[16])
            play_sdhd_duration = int(x[17])
 
            
            if _tmpdate and _tmpdate != date:
                results['data'] = os_data
                results['year'] = _tmpdate[:4]
                results['month'] = _tmpdate[4:6]
                results['day'] = _tmpdate[6:]
                all_data.append(results)
                results = {}
                os_data = []
            if _value == "no":
                #os_data.insert(0,{'os':os})
                #ss = "'os':%s" % os
                #print _os_id
                #print _tmpdate
                #print "end"
                #if _tmpdate == "":
                #    _tmpdate = "20120301"
                if _os_id == "ios":
                    _os_id = "iOS"
                if _os_id == "android":
                    _os_id = "Android"
                if _os_id == "wp7":
                    _os_id = "WP7"
                
                if _dt == "pad":
                    _dt = "Pad"
                if _dt == "phone":
                    _dt = "Phone"
                
                if _pm == "qudao":
                    _pm = 2
                if _pm == "changshang":
                    _pm = 1
                
                if pm == 3:
                    pm = 1
                
                pm_cn = ""
                if (pm == 1 or pm == 3):
                    pm_cn = u"厂商内置"
                elif pm == 2:
                    pm_cn = u"渠道推广"
                
                #print _tmpdate
                #以下是条件判断的设置    
                if os != 'FreeWap':
                    if (_os_id == "no") and (_dt == "no") and (_pm == "no") :
                        
                        play_resptime,play_times,draw_resptime,draw_times,getVideoDetail_resptime,getVideoDetail_times = clientcache.getJsondata(x[0],table_name,st_datestr,et_datestr,x[1],"no","no")
                        
                        os_data.insert(0,{'os':os, 'pv':pv, 'uv':uv, 'vv':vv, 'nu': nu,'before_duration' : before_duration,'before_times' : before_times,'duration' : duration,
            'complete' : complete,
            'play_load_duration' : play_load_duration,
            'play_load_times' : play_load_times,
            'play_hdsd_times' : play_hdsd_times,
            'play_hdsd_duration' : play_hdsd_duration,
            'play_sdhd_times' : play_sdhd_times,
            'play_sdhd_duration' : play_sdhd_duration,
            'play_resptime' : play_resptime,
        'play_times' : play_times,
        'draw_resptime' : draw_resptime,
        'draw_times' : draw_times,
        'getVideoDetail_resptime' : getVideoDetail_resptime,
        'getVideoDetail_times' : getVideoDetail_times,
            
            })
                    elif (_os_id != "no") and (_dt == "no") and (_pm == "no") :
                        if _os_id == os:
                            play_resptime,play_times,draw_resptime,draw_times,getVideoDetail_resptime,getVideoDetail_times = clientcache.getJsondata(x[0],table_name,st_datestr,et_datestr,x[1],x[2],"no")
                            os_data.insert(0,{'os':os,'type':type1,'pv':pv, 'uv':uv, 'vv':vv, 'nu': nu,'before_duration' : before_duration,'before_times' : before_times,'duration' : duration,
            'complete' : complete,
            'play_load_duration' : play_load_duration,
            'play_load_times' : play_load_times,
            'play_hdsd_times' : play_hdsd_times,
            'play_hdsd_duration' : play_hdsd_duration,
            'play_sdhd_times' : play_sdhd_times,
            'play_sdhd_duration' : play_sdhd_duration,
           'play_times' : play_times,
           'play_resptime' : play_resptime,
        'draw_resptime' : draw_resptime,
        'draw_times' : draw_times,
        'getVideoDetail_resptime' : getVideoDetail_resptime,
        'getVideoDetail_times' : getVideoDetail_times,})
                    elif (_os_id == "no") and (_dt != "no") and (_pm == "no") :
                        
                        if _dt == type1:
                            play_resptime,play_times,draw_resptime,draw_times,getVideoDetail_resptime,getVideoDetail_times = clientcache.getJsondata(x[0],table_name,st_datestr,et_datestr,x[1],x[2],"no")
                            os_data.insert(0,{'os':os,'type':type1, 'pv':pv, 'uv':uv, 'vv':vv, 'nu': nu,'before_duration' : before_duration,'before_times' : before_times,'duration' : duration,
            'complete' : complete,
            'play_load_duration' : play_load_duration,
            'play_load_times' : play_load_times,
            'play_hdsd_times' : play_hdsd_times,
            'play_hdsd_duration' : play_hdsd_duration,
            'play_sdhd_times' : play_sdhd_times,
            'play_sdhd_duration' : play_sdhd_duration,
            'play_times' : play_times,
            'play_resptime' : play_resptime,
        'draw_resptime' : draw_resptime,
        'draw_times' : draw_times,
        'getVideoDetail_resptime' : getVideoDetail_resptime,
        'getVideoDetail_times' : getVideoDetail_times,})
                        
                    elif (_os_id == "no") and (_dt == "no") and (_pm != "no") :
                        if _pm == pm:
                            play_resptime,play_times,draw_resptime,draw_times,getVideoDetail_resptime,getVideoDetail_times = clientcache.getJsondata(x[0],table_name,st_datestr,et_datestr,x[1],"no",pm)
                            os_data.insert(0,{'os':os,'pv':pv, 'uv':uv, 'vv':vv, 'nu': nu,'pm':pm_cn,'before_duration' : before_duration,'before_times' : before_times,'duration' : duration,
            'complete' : complete,
            'play_load_duration' : play_load_duration,
            'play_load_times' : play_load_times,
            'play_hdsd_times' : play_hdsd_times,
            'play_hdsd_duration' : play_hdsd_duration,
            'play_sdhd_times' : play_sdhd_times,
            'play_sdhd_duration' : play_sdhd_duration,
            'play_times' : play_times,
            'play_resptime' : play_resptime,
        'draw_resptime' : draw_resptime,
        'draw_times' : draw_times,
        'getVideoDetail_resptime' : getVideoDetail_resptime,
        'getVideoDetail_times' : getVideoDetail_times,})
                       
                    elif (_os_id != "no") and (_dt != "no") and (_pm != "no") :
                        
                        if _os_id == os and _dt == type1 and _pm == pm:
                            play_resptime,play_times,draw_resptime,draw_times,getVideoDetail_resptime,getVideoDetail_times = clientcache.getJsondata(x[0],table_name,st_datestr,et_datestr,x[1],x[2],pm)
                            os_data.insert(0,{'os':os,'type':type1, 'pv':pv, 'uv':uv, 'vv':vv, 'nu': nu,'pm':pm_cn,'before_duration' : before_duration,'before_times' : before_times,'duration' : duration,
            'complete' : complete,
            'play_load_duration' : play_load_duration,
            'play_load_times' : play_load_times,
            'play_hdsd_times' : play_hdsd_times,
            'play_hdsd_duration' : play_hdsd_duration,
            'play_sdhd_times' : play_sdhd_times,
            'play_resptime' : play_resptime,
            'play_sdhd_duration' : play_sdhd_duration,
            'play_times' : play_times,
        'draw_resptime' : draw_resptime,
        'draw_times' : draw_times,
        'getVideoDetail_resptime' : getVideoDetail_resptime,
        'getVideoDetail_times' : getVideoDetail_times,})
                            
                       
                    elif (_os_id == "no") and (_dt != "no") and (_pm != "no") :
                        if _dt == type1 and _pm == pm:
                            play_resptime,play_times,draw_resptime,draw_times,getVideoDetail_resptime,getVideoDetail_times = clientcache.getJsondata(x[0],table_name,st_datestr,et_datestr,x[1],x[2],pm)    
                            os_data.insert(0,{'os':os,'type':type1, 'pv':pv, 'uv':uv, 'vv':vv, 'nu': nu,'pm':pm_cn,'before_duration' : before_duration,'before_times' : before_times,'duration' : duration,
            'complete' : complete,
            'play_load_duration' : play_load_duration,
            'play_load_times' : play_load_times,
            'play_hdsd_times' : play_hdsd_times,
            'play_hdsd_duration' : play_hdsd_duration,
            'play_sdhd_times' : play_sdhd_times,
            'play_sdhd_duration' : play_sdhd_duration,
            'play_times' : play_times,
            'play_resptime' : play_resptime,
        'draw_resptime' : draw_resptime,
        'draw_times' : draw_times,
        'getVideoDetail_resptime' : getVideoDetail_resptime,
        'getVideoDetail_times' : getVideoDetail_times,})
                                
                        
                    elif (_os_id != "no") and (_dt != "no") and (_pm == "no") :
                        if os == _os_id and type1 == _dt:
                            #print "fuck"
                            play_resptime,play_times,draw_resptime,draw_times,getVideoDetail_resptime,getVideoDetail_times = clientcache.getJsondata(x[0],table_name,st_datestr,et_datestr,x[1],x[2],"no")
                            os_data.insert(0,{'pm1':pm,'os':os,'type':type1, 'pv':pv, 'uv':uv, 'vv':vv, 'nu': nu,'pm':pm_cn,'before_duration' : before_duration,'before_times' : before_times,'duration' : duration,
            'complete' : complete,
            'play_load_duration' : play_load_duration,
            'play_load_times' : play_load_times,
            'play_hdsd_times' : play_hdsd_times,
            'play_hdsd_duration' : play_hdsd_duration,
            'play_sdhd_times' : play_sdhd_times,
            'play_sdhd_duration' : play_sdhd_duration,
            'play_times' : play_times,
            'play_resptime' : play_resptime,
        'draw_resptime' : draw_resptime,
        'draw_times' : draw_times,
        'getVideoDetail_resptime' : getVideoDetail_resptime,
        'getVideoDetail_times' : getVideoDetail_times,})
                               
                    elif (_os_id != "no") and (_dt == "no") and (_pm != "no") :
                        if _os_id == os and _pm == pm:
                            play_resptime,play_times,draw_resptime,draw_times,getVideoDetail_resptime,getVideoDetail_times = clientcache.getJsondata(x[0],table_name,st_datestr,et_datestr,x[1],x[2],pm)
                            os_data.insert(0,{'os':os,'type':type1, 'pv':pv, 'uv':uv, 'vv':vv, 'nu': nu,'pm':pm_cn,'before_duration' : before_duration,'before_times' : before_times,'duration' : duration,
            'complete' : complete,
            'play_load_duration' : play_load_duration,
            'play_load_times' : play_load_times,
            'play_hdsd_times' : play_hdsd_times,
            'play_hdsd_duration' : play_hdsd_duration,
            'play_sdhd_times' : play_sdhd_times,
            'play_sdhd_duration' : play_sdhd_duration,
            'play_times' : play_times,
            'play_resptime' : play_resptime,
        'draw_resptime' : draw_resptime,
        'draw_times' : draw_times,
        'getVideoDetail_resptime' : getVideoDetail_resptime,
        'getVideoDetail_times' : getVideoDetail_times,})
                    
                    _tmpdate = date           
                        
            else:
                ss = "{"
                if _value.find('os') != -1:
                    ss += "'os':%s," % os
                if _value.find('type') != -1:
                    ss += "'type':%s," % type1
                if _value.find('pv') != -1:
                    ss += "'pv':%s," % pv
                if _value.find('uv') != -1:
                    ss += "'uv':%s," % uv
                if _value.find('vv') != -1:
                    ss += "'vv':%s," % vv
                if _value.find('nu') != -1:
                    ss += "'nu':%s," % nu
                ss += "}"
                os_data.insert(0,ss)  
                _tmpdate = date
        
        c.close()
        db.close()
        
        if len(os_data) > 0 :
            results['data'] = os_data
            results['year'] = _tmpdate[:4]
            results['month'] = _tmpdate[4:6]
            results['day'] = _tmpdate[6:]
            all_data.append(results)
            results = {}
            os_data = []

        self.write({"status":"success", "items":all_data})
        self.finish()


class MainTotalUser(BaseHandler):
    def get(self): 
        os_json = clientcache.getOS()
        pidtype_json = clientcache.getPidType()
        
        _time = self.get_argument('endDate', '').strip()
        try:
            ed_datestr = None
            if _time :
                ed_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
                ed_datestr = ed_time.strftime('%Y%m%d')
            else :
                ed_time = None
        except :
            #self.write({"status": "failed", "code": 400,  "desc": "invalid argument"})
            self.send_error(400, desc='invalid argument')
            return
        
        
        
        os_data = []

        db = connectMySQL.connMySQL_stat()
        c=db.cursor()
        #sql = "SELECT date, os_id, device_type, alluser  FROM `stat_day_main` group by os_id order by alluser desc"
        if not ed_datestr :
            sql = '''select tmp_a.date, tmp_a.os_id, tmp_a.device_type, max(tmp_a.alluser)  from 
            (SELECT date, os_id, device_type, sum(alluser) alluser FROM `stat_day_total` where date<=(select max(b.date) from `stat_day_total` b) and business_type=2 and pid_stat=1 group by date, os_id, device_type order by date desc) as tmp_a 
            group by tmp_a.os_id, tmp_a.device_type'''
            #sql = "SELECT date, os_id, device_type, sum(alluser)  FROM `stat_day_main` where date = (select max(b.date) from `stat_day_main` b) and ( business_type=2 or business_type=1)  and partner_mode=3 group by date, os_id, device_type"
        else :
            sql = '''select tmp_a.date, tmp_a.os_id, tmp_a.device_type, max(tmp_a.alluser)  from 
            (SELECT date, os_id, device_type, sum(alluser) alluser FROM `stat_day_total` where date<={0}  and business_type=2 and pid_stat=1 group by date, os_id, device_type order by date desc) as tmp_a 
            group by tmp_a.os_id, tmp_a.device_type'''.format(ed_datestr)
            #sql = "SELECT distinct date, os_id, device_type, sum(alluser)  FROM `stat_day_main` where date <= {0} and ( business_type=2 or business_type=1)  and partner_mode=3 group by date, os_id, device_type".format(ed_datestr)
            
        logging.info(sql)
        
        c.execute(sql)  
        res= c.fetchall()
        for x in res:
            os = os_json.get(int(x[1])) or 'null'
            #type1 = pidtype_json.get(int(x[2])) or 'null'
            type1 = settings.device_type.get(str(x[2])) or 'unkown'
            tu = int(x[3])
            os_data.insert(0,{'os':os, 'type':type1, 'tu':tu})

        c.close()
        db.close()
        
        self.write({"status":"success", "items":os_data})
        self.finish()
        
class PromoFactoryName(BaseHandler):
    def get(self):
        
        _btype = self.get_argument('btype','video').strip()
        _ftype = self.get_argument('ftype',"8").strip() 
        resjson = clientcache.getPromoFactoryName(_btype,_ftype)
        
        self.write(resjson)
        self.finish()
 
class PromoAnalytics(BaseHandler):
    def get(self): 
        _uname = self.get_argument('uname', '').strip() or ''
        _pwd = self.get_argument('pwd','').strip() or ''
        
        cu = clientuser.UserCheck()
        userlogin = cu.check(_uname, _pwd)
        
        if not userlogin or userlogin.get('status', 'failed') != 'success' :
            self.send_error(400, desc='invalid argument')
            #self.write({"status": "failed", "code": 400,  "desc": "invalid argument"})
            #self.finish()
            return
        
        _fid = self.get_argument('fid', '0').strip()
        if userlogin.get('results') and userlogin.get('results').get('type','2') == 2 and int(_fid) != int(userlogin.get('results').get('userid', '0')):
            self.send_error(400, desc='invalid argument')
            #self.write({"status": "failed", "code": 400,  "desc": "invalid argument"})
            #self.finish()
            return
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        
        try:
            st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
        except :
            self.send_error(400, desc='invalid argument')
            #self.write({"status": "failed", "code": 400,  "desc": "invalid argument"})
            #self.finish()
            return
        
        if not _pd:
            ed_time = datetime.datetime.now()
            delta = ed_time - st_time 
            _pd =  abs(delta.days)
            
        _pd = int(_pd)
        et_time = st_time + datetime.timedelta(days=_pd)
        st_datestr = st_time.strftime('%Y%m%d')
        et_datestr = et_time.strftime('%Y%m%d')
        
        os_json = clientcache.getOS()
        pidtype_json = clientcache.getPidType()
        factory_json = clientcache.getFactoryName()
        pid_json = clientcache.getParnter()
        
        all_data = []
        results = {}
        os_data = []
        
        db = connectMySQL.connMySQL_stat()
        c=db.cursor()        
        sql = "SELECT date, f_id, pid, pv, uv, vv, newuser  FROM `stat_day_channel` WHERE date>= '{0}' and date < '{1}' and f_id={2} and partner_mode in (2,8) and pid_stat=1 ORDER BY date".format(st_datestr, et_datestr, _fid)
        logging.info(sql)
        c.execute(sql)  
        res= c.fetchall()
        _tmpdate = ''
        for x in res:
            date = str(x[0])
            
            #pname = factory_json.get(x[1],'')
            pid = x[2]
            pname = pid_json.get(pid,['',''])[0]            
            pv = x[3]
            uv = x[4]
            vv = x[5]
            nu = x[6]
            
            if _tmpdate and _tmpdate != date:
                results['data'] = os_data
                results['year'] = _tmpdate[:4]
                results['month'] = _tmpdate[4:6]
                results['day'] = _tmpdate[6:]
                all_data.append(results)
                results = {}
                os_data = []
            
            os_data.insert(0,{'pname':pname, 'pid':pid, 'pv':pv, 'uv':uv, 'vv':vv, 'nu': nu})
            _tmpdate = date
        
        c.close()
        db.close()
          
        if len(os_data) > 0 :
            results['data'] = os_data
            results['year'] = _tmpdate[:4]
            results['month'] = _tmpdate[4:6]
            results['day'] = _tmpdate[6:]
            all_data.append(results)
            results = {}
            os_data = []
        
        #test = {"items": [{"year": "2011", "data": [{"pv": 8706151, "vv": 883726, "pid": "749c360516ebe533", "uv": 379018, "pname": "mobile优酷友情合作", "nu": 883726}, {"pv": 23036219, "vv": 2646085, "pid": "749c360516ebe533", "uv": 618283, "pname": "3G门户G浏览器", "nu": 2646085}, {"pv": 20426465, "vv": 10197784, "pid": "749c360516ebe533", "uv": 177077, "pname": "百信手机网外链", "nu": 10197784}, {"pv": 5984380, "vv": 675899.0, "pid": "749c360516ebe533", "uv": 380541, "pname": "航海桌面导航", "nu": 675899.0}], "day": "20", "month": "11"}, {"year": "2011", "data": [{"pv": 7738457, "vv": 788236, "pid": "749c360516ebe533", "uv": 344861, "pname": "mobile优酷友情合作", "nu": 788236}, {"pv": 19551225, "vv": 2101659, "pid": "749c360516ebe533", "uv": 510932, "pname": "3G门户G浏览器", "nu": 2101659}, {"pv": 18427618, "vv": 9257357, "pid": "749c360516ebe533", "uv": 157920, "pname": "百信手机网外链", "nu": 9257357}, {"pv": 5501749, "vv": 607562.0, "pid": "749c360516ebe533", "uv": 346352, "pname": "航海桌面导航", "nu": 607562.0}], "day": "21", "month": "11"}, {"year": "2011", "data": [{"pv": 7954177, "vv": 815959, "pid": "749c360516ebe533", "uv": 349300, "pname": "mobile优酷友情合作", "nu": 815959}, {"pv": 17299241, "vv": 2118076, "pid": "749c360516ebe533", "uv": 501143, "pname": "3G门户G浏览器", "nu": 2118076}, {"pv": 20366128, "vv": 10192610, "pid": "749c360516ebe533", "uv": 162041, "pname": "百信手机网外链", "nu": 10192610}, {"pv": 6219346, "vv": 899602, "pid": "749c360516ebe533", "uv": 363954, "pname": "航海桌面导航", "nu": 899602}], "day": "22", "month": "11"}, {"year": "2011", "data": [{"pv": 7977166, "vv": 842794, "pid": "749c360516ebe533", "uv": 348040, "pname": "mobile优酷友情合作", "nu": 842794}, {"pv": 16584716, "vv": 2097957, "pid": "749c360516ebe533", "uv": 490854, "pname": "3G门户G浏览器", "nu": 2097957}, {"pv": 20198366, "vv": 10391665, "pid": "749c360516ebe533", "uv": 161251, "pname": "百信手机网外链", "nu": 10391665}, {"pv": 5815811, "vv": 696805, "pid": "749c360516ebe533", "uv": 364588, "pname": "航海桌面导航", "nu": 696805}], "day": "23", "month": "11"}, {"year": "2011", "data": [{"pv": 7903879, "vv": 847485, "pid": "749c360516ebe533", "uv": 346739, "pname": "mobile优酷友情合作", "nu": 847485}, {"pv": 15089805, "vv": 2072196, "pid": "749c360516ebe533", "uv": 486514, "pname": "3G门户G浏览器", "nu": 2072196}, {"pv": 21005978, "vv": 10992027, "pid": "749c360516ebe533", "uv": 160747, "pname": "百信手机网外链", "nu": 10992027}, {"pv": 5907725, "vv": 714918, "pid": "749c360516ebe533", "uv": 365872, "pname": "航海桌面导航", "nu": 714918}], "day": "24", "month": "11"}, {"year": "2011", "data": [{"pv": 8036462, "vv": 859703, "pid": "749c360516ebe533", "uv": 351217, "pname": "mobile优酷友情合作", "nu": 859703}, {"pv": 16574256, "vv": 2147187, "pid": "749c360516ebe533", "uv": 508284, "pname": "3G门户G浏览器", "nu": 2147187}, {"pv": 20814242, "vv": 10802160, "pid": "749c360516ebe533", "uv": 166903, "pname": "百信手机网外链", "nu": 10802160}, {"pv": 5869896, "vv": 742478, "pid": "749c360516ebe533", "uv": 370612, "pname": "航海桌面导航", "nu": 742478}], "day": "25", "month": "11"}, {"year": "2011", "data": [{"pv": 9069765, "vv": 972571, "pid": "749c360516ebe533", "uv": 387447, "pname": "mobile优酷友情合作", "nu": 972571}, {"pv": 19110457, "vv": 2686480, "pid": "749c360516ebe533", "uv": 607180, "pname": "3G门户G浏览器", "nu": 2686480}, {"pv": 22990850, "vv": 12016920, "pid": "749c360516ebe533", "uv": 189509, "pname": "百信手机网外链", "nu": 12016920}, {"pv": 6409802, "vv": 819128, "pid": "749c360516ebe533", "uv": 408271, "pname": "航海桌面导航", "nu": 819128}], "day": "26", "month": "11"}, {"year": "2011", "data": [{"pv": 5164029, "vv": 905470, "pid": "749c360516ebe533", "uv": 402251, "pname": "mobile优酷友情合作", "nu": 905470}, {"pv": 22663416, "vv": 2959138, "pid": "749c360516ebe533", "uv": 625509, "pname": "3G门户G浏览器", "nu": 2959138}, {"pv": 22769949, "vv": 12005075, "pid": "749c360516ebe533", "uv": 194499, "pname": "百信手机网外链", "nu": 12005075}, {"pv": 6496387, "vv": 824110, "pid": "749c360516ebe533", "uv": 405406, "pname": "航海桌面导航", "nu": 824110}], "day": "27", "month": "11"}, {"year": "2011", "data": [{"pv": 7883670, "vv": 923891, "pid": "749c360516ebe533", "uv": 364508, "pname": "mobile优酷友情合作", "nu": 923891}, {"pv": 16813831, "vv": 2227148, "pid": "749c360516ebe533", "uv": 523621, "pname": "3G门户G浏览器", "nu": 2227148}, {"pv": 21876510, "vv": 11389919, "pid": "749c360516ebe533", "uv": 177008, "pname": "百信手机网外链", "nu": 11389919}, {"pv": 6182231, "vv": 786666, "pid": "749c360516ebe533", "uv": 377465, "pname": "航海桌面导航", "nu": 786666}], "day": "28", "month": "11"}, {"year": "2011", "data": [{"pv": 8932697, "vv": 979964, "pid": "749c360516ebe533", "uv": 371687, "pname": "mobile优酷友情合作", "nu": 979964}, {"pv": 18295828, "vv": 2271816, "pid": "749c360516ebe533", "uv": 529236, "pname": "3G门户G浏览器", "nu": 2271816}, {"pv": 24524788, "vv": 12383988, "pid": "749c360516ebe533", "uv": 179472, "pname": "百信手机网外链", "nu": 12383988}, {"pv": 7263753, "vv": 960556, "pid": "749c360516ebe533", "uv": 398384, "pname": "航海桌面导航", "nu": 960556}], "day": "29", "month": "11"}, {"year": "2011", "data": [{"pv": 9555887, "vv": 1046894, "pid": "749c360516ebe533", "uv": 383029, "pname": "mobile优酷友情合作", "nu": 1046894}, {"pv": 17147726, "vv": 2320942, "pid": "749c360516ebe533", "uv": 530421, "pname": "3G门户G浏览器", "nu": 2320942}, {"pv": 26100803, "vv": 13301933, "pid": "749c360516ebe533", "uv": 184759, "pname": "百信手机网外链", "nu": 13301933}, {"pv": 7837226, "vv": 1065946, "pid": "749c360516ebe533", "uv": 462942, "pname": "航海桌面导航", "nu": 1065946}], "day": "30", "month": "11"}, {"year": "2011", "data": [{"pv": 9191284, "vv": 997910, "pid": "749c360516ebe533", "uv": 378109, "pname": "mobile优酷友情合作", "nu": 997910}, {"pv": 17538103, "vv": 2212043, "pid": "749c360516ebe533", "uv": 508844, "pname": "3G门户G浏览器", "nu": 2212043}, {"pv": 23764115, "vv": 12167367, "pid": "749c360516ebe533", "uv": 182590, "pname": "百信手机网外链", "nu": 12167367}, {"pv": 7159327, "vv": 898155, "pid": "749c360516ebe533", "uv": 455937, "pname": "航海桌面导航", "nu": 898155}], "day": "01", "month": "12"}, {"year": "2011", "data": [{"pv": 8746707, "vv": 944695, "pid": "749c360516ebe533", "uv": 369130, "pname": "mobile优酷友情合作", "nu": 944695}, {"pv": 20920133, "vv": 2218533, "pid": "749c360516ebe533", "uv": 515960, "pname": "3G门户G浏览器", "nu": 2218533}, {"pv": 22158746, "vv": 11385687, "pid": "749c360516ebe533", "uv": 176859, "pname": "百信手机网外链", "nu": 11385687}, {"pv": 6573226, "vv": 820262, "pid": "749c360516ebe533", "uv": 429128, "pname": "航海桌面导航", "nu": 820262}], "day": "02", "month": "12"}, {"year": "2011", "data": [{"pv": 9729478, "vv": 1075297, "pid": "749c360516ebe533", "uv": 399538, "pname": "mobile优酷友情合作", "nu": 1075297}, {"pv": 25240817, "vv": 2707561, "pid": "749c360516ebe533", "uv": 601559, "pname": "3G门户G浏览器", "nu": 2707561}, {"pv": 23853896, "vv": 12166467, "pid": "749c360516ebe533", "uv": 197107, "pname": "百信手机网外链", "nu": 12166467}, {"pv": 6951907, "vv": 883009, "pid": "749c360516ebe533", "uv": 448783, "pname": "航海桌面导航", "nu": 883009}], "day": "03", "month": "12"}, {"year": "2011", "data": [{"pv": 6553890, "vv": 1000655, "pid": "749c360516ebe533", "uv": 410977, "pname": "mobile优酷友情合作", "nu": 1000655}, {"pv": 26534414, "vv": 2949384, "pid": "749c360516ebe533", "uv": 657332, "pname": "3G门户G浏览器", "nu": 2949384}, {"pv": 20255624, "vv": 9431825, "pid": "749c360516ebe533", "uv": 202836, "pname": "百信手机网外链", "nu": 9431825}, {"pv": 6194333, "vv": 709191, "pid": "749c360516ebe533", "uv": 401298, "pname": "航海桌面导航", "nu": 709191}], "day": "04", "month": "12"}, {"year": "2011", "data": [{"pv": 7504068, "vv": 931829, "pid": "749c360516ebe533", "uv": 372472, "pname": "mobile优酷友情合作", "nu": 931829}, {"pv": 26728075, "vv": 2215458, "pid": "749c360516ebe533", "uv": 556967, "pname": "3G门户G浏览器", "nu": 2215458}, {"pv": 22015006, "vv": 11073917, "pid": "749c360516ebe533", "uv": 181164, "pname": "百信手机网外链", "nu": 11073917}, {"pv": 6398145, "vv": 790298, "pid": "749c360516ebe533", "uv": 404533, "pname": "航海桌面导航", "nu": 790298}], "day": "05", "month": "12"}, {"year": "2011", "data": [{"pv": 9102575, "vv": 1062570, "pid": "749c360516ebe533", "uv": 375255, "pname": "mobile优酷友情合作", "nu": 1062570}, {"pv": 22657579, "vv": 2378515, "pid": "749c360516ebe533", "uv": 519891, "pname": "3G门户G浏览器", "nu": 2378515}, {"pv": 25411025, "vv": 12908338, "pid": "749c360516ebe533", "uv": 183900, "pname": "百信手机网外链", "nu": 12908338}, {"pv": 7267270, "vv": 921841, "pid": "749c360516ebe533", "uv": 431079, "pname": "航海桌面导航", "nu": 921841}], "day": "06", "month": "12"}, {"year": "2011", "data": [{"pv": 9323365, "vv": 1093411, "pid": "749c360516ebe533", "uv": 380987, "pname": "mobile优酷友情合作", "nu": 1093411}, {"pv": 27118625, "vv": 2324804, "pid": "749c360516ebe533", "uv": 509508, "pname": "3G门户G浏览器", "nu": 2324804}, {"pv": 27824591, "vv": 13416846, "pid": "749c360516ebe533", "uv": 201491, "pname": "百信手机网外链", "nu": 13416846}, {"pv": 8086168, "vv": 1000817, "pid": "749c360516ebe533", "uv": 442779, "pname": "航海桌面导航", "nu": 1000817}], "day": "07", "month": "12"}, {"year": "2011", "data": [{"pv": 9038836, "vv": 1063200, "pid": "749c360516ebe533", "uv": 373748, "pname": "mobile优酷友情合作", "nu": 1063200}, {"pv": 17233370, "vv": 2134431, "pid": "749c360516ebe533", "uv": 508371, "pname": "3G门户G浏览器", "nu": 2134431}, {"pv": 26251026, "vv": 12625185, "pid": "749c360516ebe533", "uv": 205565, "pname": "百信手机网外链", "nu": 12625185}, {"pv": 7313013, "vv": 902782, "pid": "749c360516ebe533", "uv": 411684, "pname": "航海桌面导航", "nu": 902782}], "day": "08", "month": "12"}, {"year": "2011", "data": [{"pv": 8363367, "vv": 1045071, "pid": "749c360516ebe533", "uv": 371220, "pname": "mobile优酷友情合作", "nu": 1045071}, {"pv": 17447010, "vv": 2132177, "pid": "749c360516ebe533", "uv": 481472, "pname": "3G门户G浏览器", "nu": 2132177}, {"pv": 23802977, "vv": 11606653, "pid": "749c360516ebe533", "uv": 208438, "pname": "百信手机网外链", "nu": 11606653}, {"pv": 6693872, "vv": 937565, "pid": "749c360516ebe533", "uv": 398948, "pname": "航海桌面导航", "nu": 937565}], "day": "09", "month": "12"}, {"year": "2011", "data": [{"pv": 9525712, "vv": 1127967, "pid": "749c360516ebe533", "uv": 399203, "pname": "mobile优酷友情合作", "nu": 1127967}, {"pv": 21035193, "vv": 2485316, "pid": "749c360516ebe533", "uv": 550803, "pname": "3G门户G浏览器", "nu": 2485316}, {"pv": 26775777, "vv": 12982224, "pid": "749c360516ebe533", "uv": 239143, "pname": "百信手机网外链", "nu": 12982224}, {"pv": 6780413, "vv": 835476, "pid": "749c360516ebe533", "uv": 422789, "pname": "航海桌面导航", "nu": 835476}], "day": "10", "month": "12"}, {"year": "2011", "data": [{"pv": 9700728, "vv": 1156906, "pid": "749c360516ebe533", "uv": 404359, "pname": "mobile优酷友情合作", "nu": 1156906}, {"pv": 18842952, "vv": 2470392, "pid": "749c360516ebe533", "uv": 546650, "pname": "3G门户G浏览器", "nu": 2470392}, {"pv": 27251966, "vv": 13014231, "pid": "749c360516ebe533", "uv": 249194, "pname": "百信手机网外链", "nu": 13014231}, {"pv": 6725342, "vv": 812185, "pid": "749c360516ebe533", "uv": 417197, "pname": "航海桌面导航", "nu": 812185}], "day": "11", "month": "12"}, {"year": "2011", "data": [{"pv": 8318720, "vv": 1010236, "pid": "749c360516ebe533", "uv": 361017, "pname": "mobile优酷友情合作", "nu": 1010236}, {"pv": 12905152, "vv": 1890186, "pid": "749c360516ebe533", "uv": 446430, "pname": "3G门户G浏览器", "nu": 1890186}, {"pv": 24365788, "vv": 11680267, "pid": "749c360516ebe533", "uv": 216079, "pname": "百信手机网外链", "nu": 11680267}, {"pv": 6134800, "vv": 730836, "pid": "749c360516ebe533", "uv": 388648, "pname": "航海桌面导航", "nu": 730836}], "day": "12", "month": "12"}, {"year": "2011", "data": [{"pv": 8689454, "vv": 1069416, "pid": "749c360516ebe533", "uv": 371320, "pname": "mobile优酷友情合作", "nu": 1069416}, {"pv": 14424782, "vv": 1908065, "pid": "749c360516ebe533", "uv": 451278, "pname": "3G门户G浏览器", "nu": 1908065}, {"pv": 25477197, "vv": 12223510, "pid": "749c360516ebe533", "uv": 223816, "pname": "百信手机网外链", "nu": 12223510}, {"pv": 6353900, "vv": 764547, "pid": "749c360516ebe533", "uv": 396732, "pname": "航海桌面导航", "nu": 764547}], "day": "13", "month": "12"}, {"year": "2011", "data": [{"pv": 8762564, "vv": 1100199, "pid": "749c360516ebe533", "uv": 375636, "pname": "mobile优酷友情合作", "nu": 1100199}, {"pv": 15790426, "vv": 1933915, "pid": "749c360516ebe533", "uv": 447268, "pname": "3G门户G浏览器", "nu": 1933915}, {"pv": 25910457, "vv": 12576917, "pid": "749c360516ebe533", "uv": 226918, "pname": "百信手机网外链", "nu": 12576917}, {"pv": 6392187, "vv": 788946, "pid": "749c360516ebe533", "uv": 395650, "pname": "航海桌面导航", "nu": 788946}], "day": "14", "month": "12"}, {"year": "2011", "data": [{"pv": 8648849, "vv": 1117817, "pid": "749c360516ebe533", "uv": 381679, "pname": "mobile优酷友情合作", "nu": 1117817}, {"pv": 14460326, "vv": 1993575, "pid": "749c360516ebe533", "uv": 458094, "pname": "3G门户G浏览器", "nu": 1993575}, {"pv": 26274120, "vv": 12717041, "pid": "749c360516ebe533", "uv": 234441, "pname": "百信手机网外链", "nu": 12717041}, {"pv": 6442292, "vv": 801841, "pid": "749c360516ebe533", "uv": 404290, "pname": "航海桌面导航", "nu": 801841}], "day": "15", "month": "12"}, {"year": "2011", "data": [{"pv": 8974934, "vv": 1135333, "pid": "749c360516ebe533", "uv": 384968, "pname": "mobile优酷友情合作", "nu": 1135333}, {"pv": 14935738, "vv": 1968406, "pid": "749c360516ebe533", "uv": 460287, "pname": "3G门户G浏览器", "nu": 1968406}, {"pv": 26481000, "vv": 12890380, "pid": "749c360516ebe533", "uv": 238530, "pname": "百信手机网外链", "nu": 12890380}, {"pv": 6517663, "vv": 807037, "pid": "749c360516ebe533", "uv": 411766, "pname": "航海桌面导航", "nu": 807037}], "day": "16", "month": "12"}, {"year": "2011", "data": [{"pv": 10026462, "vv": 1236730, "pid": "749c360516ebe533", "uv": 420494, "pname": "mobile优酷友情合作", "nu": 1236730}, {"pv": 17893920, "vv": 2373075, "pid": "749c360516ebe533", "uv": 533109, "pname": "3G门户G浏览器", "nu": 2373075}, {"pv": 29427041, "vv": 14269110, "pid": "749c360516ebe533", "uv": 276155, "pname": "百信手机网外链", "nu": 14269110}, {"pv": 7106385, "vv": 902434, "pid": "749c360516ebe533", "uv": 441599, "pname": "航海桌面导航", "nu": 902434}], "day": "17", "month": "12"}, {"year": "2011", "data": [{"pv": 10245069, "vv": 1289253, "pid": "749c360516ebe533", "uv": 428359, "pname": "mobile优酷友情合作", "nu": 1289253}, {"pv": 16366469, "vv": 2416836, "pid": "749c360516ebe533", "uv": 535023, "pname": "3G门户G浏览器", "nu": 2416836}, {"pv": 30343887, "vv": 14817690, "pid": "749c360516ebe533", "uv": 285791, "pname": "百信手机网外链", "nu": 14817690}, {"pv": 7162604, "vv": 903269, "pid": "749c360516ebe533", "uv": 451413, "pname": "航海桌面导航", "nu": 903269}], "day": "18", "month": "12"}, {"year": "2011", "data": [{"pv": 8928252, "vv": 1110394, "pid": "749c360516ebe533", "uv": 389020, "pname": "mobile优酷友情合作", "nu": 1110394}, {"pv": 12521422, "vv": 1880090, "pid": "749c360516ebe533", "uv": 448916, "pname": "3G门户G浏览器", "nu": 1880090}, {"pv": 26264948, "vv": 12763681, "pid": "749c360516ebe533", "uv": 248776, "pname": "百信手机网外链", "nu": 12763681}, {"pv": 6481151, "vv": 803660, "pid": "749c360516ebe533", "uv": 407620, "pname": "航海桌面导航", "nu": 803660}], "day": "19", "month": "12"}]}
        self.write({"status":"success","items":all_data})
        self.finish()
        
class FactoryName(BaseHandler):
    def get(self):
        _btype = self.get_argument('btype','video').strip()
        #test = {"items":[{"os":"Android", "fname":"华为 huawei", "fid":"2"},{"os":"Android", "fname":"多普达 HTC", "fid":"5"},{"os":"Android", "fname":"联想 lenovo", "fid":"10"},{"os":"Android", "fname":"三星 SAMSUNG", "fid":"12"},{"os":"Android", "fname":"优酷 youku", "fid":"14"},{"os":"Android", "fname":"天宇 K-Touch", "fid":"16"},{"os":"Android", "fname":"点心OS Dianxin", "fid":"29"},{"os":"Android", "fname":"LG", "fid":"75"},{"os":"Android", "fname":"MOTO", "fid":"77"},{"os":"Android", "fname":"oppo", "fid":"110"},{"os":"Android", "fname":"TCL", "fid":"144"},{"os":"Android", "fname":"索尼", "fid":"159"},{"os":"Android", "fname":"海尔", "fid":"161"},{"os":"Android", "fname":"海尔", "fid":"161"},{"os":"Android", "fname":"步步高", "fid":"170"},{"os":"Android", "fname":"酷派", "fid":"177"},{"os":"Android", "fname":"壹人壹本", "fid":"181"},{"os":"Android", "fname":"小米科技", "fid":"184"},{"os":"Android", "fname":"炬力", "fid":"185"},{"os":"Android", "fname":"康佳", "fid":"187"},{"os":"Android", "fname":"金立", "fid":"194"},{"os":"Android", "fname":"天语", "fid":"196"},{"os":"Android", "fname":"宏基", "fid":"197"},{"os":"Android", "fname":"广东移动", "fid":"198"},{"os":"Android", "fname":"海信", "fid":"199"},{"os":"Android", "fname":"万利达", "fid":"202"},{"os":"Android", "fname":"驰为", "fid":"205"},{"os":"Android", "fname":"博泰", "fid":"206"},{"os":"Android", "fname":"网合", "fid":"208"},{"os":"Android", "fname":"中兴", "fid":"211"},{"os":"Android", "fname":"杰拓", "fid":"213"},{"os":"Android", "fname":"大唐", "fid":"215"},{"os":"Android", "fname":"大唐", "fid":"215"},{"os":"Android", "fname":"高通", "fid":"217"},{"os":"bada", "fname":"三星 SAMSUNG", "fid":"12"},{"os":"java", "fname":"天奕达", "fid":"212"},{"os":"MTK", "fname":"MTK MTK", "fid":"18"},{"os":"MTK", "fname":"oppo", "fid":"110"},{"os":"MTK", "fname":"TCL", "fid":"144"},{"os":"MTK", "fname":"步步高", "fid":"170"},{"os":"MTK", "fname":"奥克斯", "fid":"214"},{"os":"Other", "fname":"诺基亚 nokia", "fid":"3"},{"os":"Other", "fname":"黑莓 blackberry", "fid":"26"},{"os":"unknown", "fname":"华为 huawei", "fid":"2"},{"os":"unknown", "fname":"爱国者 aigo", "fid":"20"},{"os":"unknown", "fname":"TCL", "fid":"144"},{"os":"Windows Phone", "fname":"多普达 HTC", "fid":"5"},{"os":"Windows Phone", "fname":"三星 SAMSUNG", "fid":"12"},{"os":"Windows Phone", "fname":"天宇 K-Touch", "fid":"16"},{"os":"Windows Phone", "fname":"通用", "fid":"140"}]}
        resjson = clientcache.getPidFactoryName(_btype)
        
        self.write(resjson)
        self.finish()

class FactoryAnalytics(BaseHandler):
    def get(self): 
        parnter_json = clientcache.getParnter()
        getFname
        _fid = self.get_argument('fid', '').strip()
        _osid = self.get_argument('osid','').strip()
        _staDate = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd', '7').strip()
        
        if not _pd :
            _pd = 7
        else:
            _pd = int(_pd)
        
        if not _fid or not _osid :
            self.send_error(400, desc='invalid argument')
            #self.write({"status": "failed", "code": 400,  "desc": "invalid argument"})
            #self.finish()
            return
        
        st_time = ''
        et_time = ''
        
        if not _staDate:
            _time = datetime.datetime.now() + datetime.timedelta(days=-1)
            st_time = (_time + datetime.timedelta(days=-_pd)).strftime( '%Y%m%d')
            et_time = _time.strftime( '%Y%m%d')
        else :
            try:
                #st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
                _time = datetime.datetime.strptime(_staDate, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                #self.write({"status": "failed", "code": 400,  "desc": "invalid argument"})
                #self.finish()
                return
            st_time= _time.strftime( '%Y%m%d')
            et_time = (_time + datetime.timedelta(days=_pd)).strftime( '%Y%m%d')
        
        all_data = []
        results = {}
        os_data = []

        db = connectMySQL.connMySQL_stat()
        c=db.cursor()        
        sql = "SELECT date, pv, uv, vv, newuser, pid  FROM `stat_day_factory` WHERE date>= '{0}' and date < '{1}' and  f_id={2} and os_id={3}  and partner_mode=1 and pid_stat=1   order by date".format(st_time, et_time, _fid, _osid)
        logging.info(sql)
        c.execute(sql)  
        res= c.fetchall()
        _tmpdate = ''
        for x in res:
            date = str(x[0])
            pv = int(x[1])
            uv = int(x[2])
            vv = int(x[3])
            nu = int(x[4])
            pid = x[5]

            if _tmpdate and _tmpdate != date:
                results['data'] = os_data
                results['year'] = _tmpdate[:4]
                results['month'] = _tmpdate[4:6]
                results['day'] = _tmpdate[6:]
                all_data.append(results)
                results = {}
                os_data = []
            
            os_data.insert(0,{'uv':uv, 'nu':nu, 'pid':pid, 'pname':parnter_json.get(pid,['',''])[0], 'ph':parnter_json.get(pid,['',''])[1]})
            _tmpdate = date
        
        c.close()
        db.close()
        
        if len(os_data) > 0 :
            results['data'] = os_data
            results['year'] = _tmpdate[:4]
            results['month'] = _tmpdate[4:6]
            results['day'] = _tmpdate[6:]
            all_data.append(results)
            results = {}
            os_data = []
        
        #print all_data
        #test = {"items": [{"year": "2011", "data": [{"pv": 8706151, "vv": 883726, "pid": "749c360516ebe533", "uv": 379018, "pname": "mobile优酷友情合作", "nu": 883726}, {"pv": 23036219, "vv": 2646085, "pid": "749c360516ebe533", "uv": 618283, "pname": "3G门户G浏览器", "nu": 2646085}, {"pv": 20426465, "vv": 10197784, "pid": "749c360516ebe533", "uv": 177077, "pname": "百信手机网外链", "nu": 10197784}, {"pv": 5984380, "vv": 675899.0, "pid": "749c360516ebe533", "uv": 380541, "pname": "航海桌面导航", "nu": 675899.0}], "day": "20", "month": "11"}, {"year": "2011", "data": [{"pv": 7738457, "vv": 788236, "pid": "749c360516ebe533", "uv": 344861, "pname": "mobile优酷友情合作", "nu": 788236}, {"pv": 19551225, "vv": 2101659, "pid": "749c360516ebe533", "uv": 510932, "pname": "3G门户G浏览器", "nu": 2101659}, {"pv": 18427618, "vv": 9257357, "pid": "749c360516ebe533", "uv": 157920, "pname": "百信手机网外链", "nu": 9257357}, {"pv": 5501749, "vv": 607562.0, "pid": "749c360516ebe533", "uv": 346352, "pname": "航海桌面导航", "nu": 607562.0}], "day": "21", "month": "11"}, {"year": "2011", "data": [{"pv": 7954177, "vv": 815959, "pid": "749c360516ebe533", "uv": 349300, "pname": "mobile优酷友情合作", "nu": 815959}, {"pv": 17299241, "vv": 2118076, "pid": "749c360516ebe533", "uv": 501143, "pname": "3G门户G浏览器", "nu": 2118076}, {"pv": 20366128, "vv": 10192610, "pid": "749c360516ebe533", "uv": 162041, "pname": "百信手机网外链", "nu": 10192610}, {"pv": 6219346, "vv": 899602, "pid": "749c360516ebe533", "uv": 363954, "pname": "航海桌面导航", "nu": 899602}], "day": "22", "month": "11"}, {"year": "2011", "data": [{"pv": 7977166, "vv": 842794, "pid": "749c360516ebe533", "uv": 348040, "pname": "mobile优酷友情合作", "nu": 842794}, {"pv": 16584716, "vv": 2097957, "pid": "749c360516ebe533", "uv": 490854, "pname": "3G门户G浏览器", "nu": 2097957}, {"pv": 20198366, "vv": 10391665, "pid": "749c360516ebe533", "uv": 161251, "pname": "百信手机网外链", "nu": 10391665}, {"pv": 5815811, "vv": 696805, "pid": "749c360516ebe533", "uv": 364588, "pname": "航海桌面导航", "nu": 696805}], "day": "23", "month": "11"}, {"year": "2011", "data": [{"pv": 7903879, "vv": 847485, "pid": "749c360516ebe533", "uv": 346739, "pname": "mobile优酷友情合作", "nu": 847485}, {"pv": 15089805, "vv": 2072196, "pid": "749c360516ebe533", "uv": 486514, "pname": "3G门户G浏览器", "nu": 2072196}, {"pv": 21005978, "vv": 10992027, "pid": "749c360516ebe533", "uv": 160747, "pname": "百信手机网外链", "nu": 10992027}, {"pv": 5907725, "vv": 714918, "pid": "749c360516ebe533", "uv": 365872, "pname": "航海桌面导航", "nu": 714918}], "day": "24", "month": "11"}, {"year": "2011", "data": [{"pv": 8036462, "vv": 859703, "pid": "749c360516ebe533", "uv": 351217, "pname": "mobile优酷友情合作", "nu": 859703}, {"pv": 16574256, "vv": 2147187, "pid": "749c360516ebe533", "uv": 508284, "pname": "3G门户G浏览器", "nu": 2147187}, {"pv": 20814242, "vv": 10802160, "pid": "749c360516ebe533", "uv": 166903, "pname": "百信手机网外链", "nu": 10802160}, {"pv": 5869896, "vv": 742478, "pid": "749c360516ebe533", "uv": 370612, "pname": "航海桌面导航", "nu": 742478}], "day": "25", "month": "11"}, {"year": "2011", "data": [{"pv": 9069765, "vv": 972571, "pid": "749c360516ebe533", "uv": 387447, "pname": "mobile优酷友情合作", "nu": 972571}, {"pv": 19110457, "vv": 2686480, "pid": "749c360516ebe533", "uv": 607180, "pname": "3G门户G浏览器", "nu": 2686480}, {"pv": 22990850, "vv": 12016920, "pid": "749c360516ebe533", "uv": 189509, "pname": "百信手机网外链", "nu": 12016920}, {"pv": 6409802, "vv": 819128, "pid": "749c360516ebe533", "uv": 408271, "pname": "航海桌面导航", "nu": 819128}], "day": "26", "month": "11"}, {"year": "2011", "data": [{"pv": 5164029, "vv": 905470, "pid": "749c360516ebe533", "uv": 402251, "pname": "mobile优酷友情合作", "nu": 905470}, {"pv": 22663416, "vv": 2959138, "pid": "749c360516ebe533", "uv": 625509, "pname": "3G门户G浏览器", "nu": 2959138}, {"pv": 22769949, "vv": 12005075, "pid": "749c360516ebe533", "uv": 194499, "pname": "百信手机网外链", "nu": 12005075}, {"pv": 6496387, "vv": 824110, "pid": "749c360516ebe533", "uv": 405406, "pname": "航海桌面导航", "nu": 824110}], "day": "27", "month": "11"}, {"year": "2011", "data": [{"pv": 7883670, "vv": 923891, "pid": "749c360516ebe533", "uv": 364508, "pname": "mobile优酷友情合作", "nu": 923891}, {"pv": 16813831, "vv": 2227148, "pid": "749c360516ebe533", "uv": 523621, "pname": "3G门户G浏览器", "nu": 2227148}, {"pv": 21876510, "vv": 11389919, "pid": "749c360516ebe533", "uv": 177008, "pname": "百信手机网外链", "nu": 11389919}, {"pv": 6182231, "vv": 786666, "pid": "749c360516ebe533", "uv": 377465, "pname": "航海桌面导航", "nu": 786666}], "day": "28", "month": "11"}, {"year": "2011", "data": [{"pv": 8932697, "vv": 979964, "pid": "749c360516ebe533", "uv": 371687, "pname": "mobile优酷友情合作", "nu": 979964}, {"pv": 18295828, "vv": 2271816, "pid": "749c360516ebe533", "uv": 529236, "pname": "3G门户G浏览器", "nu": 2271816}, {"pv": 24524788, "vv": 12383988, "pid": "749c360516ebe533", "uv": 179472, "pname": "百信手机网外链", "nu": 12383988}, {"pv": 7263753, "vv": 960556, "pid": "749c360516ebe533", "uv": 398384, "pname": "航海桌面导航", "nu": 960556}], "day": "29", "month": "11"}, {"year": "2011", "data": [{"pv": 9555887, "vv": 1046894, "pid": "749c360516ebe533", "uv": 383029, "pname": "mobile优酷友情合作", "nu": 1046894}, {"pv": 17147726, "vv": 2320942, "pid": "749c360516ebe533", "uv": 530421, "pname": "3G门户G浏览器", "nu": 2320942}, {"pv": 26100803, "vv": 13301933, "pid": "749c360516ebe533", "uv": 184759, "pname": "百信手机网外链", "nu": 13301933}, {"pv": 7837226, "vv": 1065946, "pid": "749c360516ebe533", "uv": 462942, "pname": "航海桌面导航", "nu": 1065946}], "day": "30", "month": "11"}, {"year": "2011", "data": [{"pv": 9191284, "vv": 997910, "pid": "749c360516ebe533", "uv": 378109, "pname": "mobile优酷友情合作", "nu": 997910}, {"pv": 17538103, "vv": 2212043, "pid": "749c360516ebe533", "uv": 508844, "pname": "3G门户G浏览器", "nu": 2212043}, {"pv": 23764115, "vv": 12167367, "pid": "749c360516ebe533", "uv": 182590, "pname": "百信手机网外链", "nu": 12167367}, {"pv": 7159327, "vv": 898155, "pid": "749c360516ebe533", "uv": 455937, "pname": "航海桌面导航", "nu": 898155}], "day": "01", "month": "12"}, {"year": "2011", "data": [{"pv": 8746707, "vv": 944695, "pid": "749c360516ebe533", "uv": 369130, "pname": "mobile优酷友情合作", "nu": 944695}, {"pv": 20920133, "vv": 2218533, "pid": "749c360516ebe533", "uv": 515960, "pname": "3G门户G浏览器", "nu": 2218533}, {"pv": 22158746, "vv": 11385687, "pid": "749c360516ebe533", "uv": 176859, "pname": "百信手机网外链", "nu": 11385687}, {"pv": 6573226, "vv": 820262, "pid": "749c360516ebe533", "uv": 429128, "pname": "航海桌面导航", "nu": 820262}], "day": "02", "month": "12"}, {"year": "2011", "data": [{"pv": 9729478, "vv": 1075297, "pid": "749c360516ebe533", "uv": 399538, "pname": "mobile优酷友情合作", "nu": 1075297}, {"pv": 25240817, "vv": 2707561, "pid": "749c360516ebe533", "uv": 601559, "pname": "3G门户G浏览器", "nu": 2707561}, {"pv": 23853896, "vv": 12166467, "pid": "749c360516ebe533", "uv": 197107, "pname": "百信手机网外链", "nu": 12166467}, {"pv": 6951907, "vv": 883009, "pid": "749c360516ebe533", "uv": 448783, "pname": "航海桌面导航", "nu": 883009}], "day": "03", "month": "12"}, {"year": "2011", "data": [{"pv": 6553890, "vv": 1000655, "pid": "749c360516ebe533", "uv": 410977, "pname": "mobile优酷友情合作", "nu": 1000655}, {"pv": 26534414, "vv": 2949384, "pid": "749c360516ebe533", "uv": 657332, "pname": "3G门户G浏览器", "nu": 2949384}, {"pv": 20255624, "vv": 9431825, "pid": "749c360516ebe533", "uv": 202836, "pname": "百信手机网外链", "nu": 9431825}, {"pv": 6194333, "vv": 709191, "pid": "749c360516ebe533", "uv": 401298, "pname": "航海桌面导航", "nu": 709191}], "day": "04", "month": "12"}, {"year": "2011", "data": [{"pv": 7504068, "vv": 931829, "pid": "749c360516ebe533", "uv": 372472, "pname": "mobile优酷友情合作", "nu": 931829}, {"pv": 26728075, "vv": 2215458, "pid": "749c360516ebe533", "uv": 556967, "pname": "3G门户G浏览器", "nu": 2215458}, {"pv": 22015006, "vv": 11073917, "pid": "749c360516ebe533", "uv": 181164, "pname": "百信手机网外链", "nu": 11073917}, {"pv": 6398145, "vv": 790298, "pid": "749c360516ebe533", "uv": 404533, "pname": "航海桌面导航", "nu": 790298}], "day": "05", "month": "12"}, {"year": "2011", "data": [{"pv": 9102575, "vv": 1062570, "pid": "749c360516ebe533", "uv": 375255, "pname": "mobile优酷友情合作", "nu": 1062570}, {"pv": 22657579, "vv": 2378515, "pid": "749c360516ebe533", "uv": 519891, "pname": "3G门户G浏览器", "nu": 2378515}, {"pv": 25411025, "vv": 12908338, "pid": "749c360516ebe533", "uv": 183900, "pname": "百信手机网外链", "nu": 12908338}, {"pv": 7267270, "vv": 921841, "pid": "749c360516ebe533", "uv": 431079, "pname": "航海桌面导航", "nu": 921841}], "day": "06", "month": "12"}, {"year": "2011", "data": [{"pv": 9323365, "vv": 1093411, "pid": "749c360516ebe533", "uv": 380987, "pname": "mobile优酷友情合作", "nu": 1093411}, {"pv": 27118625, "vv": 2324804, "pid": "749c360516ebe533", "uv": 509508, "pname": "3G门户G浏览器", "nu": 2324804}, {"pv": 27824591, "vv": 13416846, "pid": "749c360516ebe533", "uv": 201491, "pname": "百信手机网外链", "nu": 13416846}, {"pv": 8086168, "vv": 1000817, "pid": "749c360516ebe533", "uv": 442779, "pname": "航海桌面导航", "nu": 1000817}], "day": "07", "month": "12"}, {"year": "2011", "data": [{"pv": 9038836, "vv": 1063200, "pid": "749c360516ebe533", "uv": 373748, "pname": "mobile优酷友情合作", "nu": 1063200}, {"pv": 17233370, "vv": 2134431, "pid": "749c360516ebe533", "uv": 508371, "pname": "3G门户G浏览器", "nu": 2134431}, {"pv": 26251026, "vv": 12625185, "pid": "749c360516ebe533", "uv": 205565, "pname": "百信手机网外链", "nu": 12625185}, {"pv": 7313013, "vv": 902782, "pid": "749c360516ebe533", "uv": 411684, "pname": "航海桌面导航", "nu": 902782}], "day": "08", "month": "12"}, {"year": "2011", "data": [{"pv": 8363367, "vv": 1045071, "pid": "749c360516ebe533", "uv": 371220, "pname": "mobile优酷友情合作", "nu": 1045071}, {"pv": 17447010, "vv": 2132177, "pid": "749c360516ebe533", "uv": 481472, "pname": "3G门户G浏览器", "nu": 2132177}, {"pv": 23802977, "vv": 11606653, "pid": "749c360516ebe533", "uv": 208438, "pname": "百信手机网外链", "nu": 11606653}, {"pv": 6693872, "vv": 937565, "pid": "749c360516ebe533", "uv": 398948, "pname": "航海桌面导航", "nu": 937565}], "day": "09", "month": "12"}, {"year": "2011", "data": [{"pv": 9525712, "vv": 1127967, "pid": "749c360516ebe533", "uv": 399203, "pname": "mobile优酷友情合作", "nu": 1127967}, {"pv": 21035193, "vv": 2485316, "pid": "749c360516ebe533", "uv": 550803, "pname": "3G门户G浏览器", "nu": 2485316}, {"pv": 26775777, "vv": 12982224, "pid": "749c360516ebe533", "uv": 239143, "pname": "百信手机网外链", "nu": 12982224}, {"pv": 6780413, "vv": 835476, "pid": "749c360516ebe533", "uv": 422789, "pname": "航海桌面导航", "nu": 835476}], "day": "10", "month": "12"}, {"year": "2011", "data": [{"pv": 9700728, "vv": 1156906, "pid": "749c360516ebe533", "uv": 404359, "pname": "mobile优酷友情合作", "nu": 1156906}, {"pv": 18842952, "vv": 2470392, "pid": "749c360516ebe533", "uv": 546650, "pname": "3G门户G浏览器", "nu": 2470392}, {"pv": 27251966, "vv": 13014231, "pid": "749c360516ebe533", "uv": 249194, "pname": "百信手机网外链", "nu": 13014231}, {"pv": 6725342, "vv": 812185, "pid": "749c360516ebe533", "uv": 417197, "pname": "航海桌面导航", "nu": 812185}], "day": "11", "month": "12"}, {"year": "2011", "data": [{"pv": 8318720, "vv": 1010236, "pid": "749c360516ebe533", "uv": 361017, "pname": "mobile优酷友情合作", "nu": 1010236}, {"pv": 12905152, "vv": 1890186, "pid": "749c360516ebe533", "uv": 446430, "pname": "3G门户G浏览器", "nu": 1890186}, {"pv": 24365788, "vv": 11680267, "pid": "749c360516ebe533", "uv": 216079, "pname": "百信手机网外链", "nu": 11680267}, {"pv": 6134800, "vv": 730836, "pid": "749c360516ebe533", "uv": 388648, "pname": "航海桌面导航", "nu": 730836}], "day": "12", "month": "12"}, {"year": "2011", "data": [{"pv": 8689454, "vv": 1069416, "pid": "749c360516ebe533", "uv": 371320, "pname": "mobile优酷友情合作", "nu": 1069416}, {"pv": 14424782, "vv": 1908065, "pid": "749c360516ebe533", "uv": 451278, "pname": "3G门户G浏览器", "nu": 1908065}, {"pv": 25477197, "vv": 12223510, "pid": "749c360516ebe533", "uv": 223816, "pname": "百信手机网外链", "nu": 12223510}, {"pv": 6353900, "vv": 764547, "pid": "749c360516ebe533", "uv": 396732, "pname": "航海桌面导航", "nu": 764547}], "day": "13", "month": "12"}, {"year": "2011", "data": [{"pv": 8762564, "vv": 1100199, "pid": "749c360516ebe533", "uv": 375636, "pname": "mobile优酷友情合作", "nu": 1100199}, {"pv": 15790426, "vv": 1933915, "pid": "749c360516ebe533", "uv": 447268, "pname": "3G门户G浏览器", "nu": 1933915}, {"pv": 25910457, "vv": 12576917, "pid": "749c360516ebe533", "uv": 226918, "pname": "百信手机网外链", "nu": 12576917}, {"pv": 6392187, "vv": 788946, "pid": "749c360516ebe533", "uv": 395650, "pname": "航海桌面导航", "nu": 788946}], "day": "14", "month": "12"}, {"year": "2011", "data": [{"pv": 8648849, "vv": 1117817, "pid": "749c360516ebe533", "uv": 381679, "pname": "mobile优酷友情合作", "nu": 1117817}, {"pv": 14460326, "vv": 1993575, "pid": "749c360516ebe533", "uv": 458094, "pname": "3G门户G浏览器", "nu": 1993575}, {"pv": 26274120, "vv": 12717041, "pid": "749c360516ebe533", "uv": 234441, "pname": "百信手机网外链", "nu": 12717041}, {"pv": 6442292, "vv": 801841, "pid": "749c360516ebe533", "uv": 404290, "pname": "航海桌面导航", "nu": 801841}], "day": "15", "month": "12"}, {"year": "2011", "data": [{"pv": 8974934, "vv": 1135333, "pid": "749c360516ebe533", "uv": 384968, "pname": "mobile优酷友情合作", "nu": 1135333}, {"pv": 14935738, "vv": 1968406, "pid": "749c360516ebe533", "uv": 460287, "pname": "3G门户G浏览器", "nu": 1968406}, {"pv": 26481000, "vv": 12890380, "pid": "749c360516ebe533", "uv": 238530, "pname": "百信手机网外链", "nu": 12890380}, {"pv": 6517663, "vv": 807037, "pid": "749c360516ebe533", "uv": 411766, "pname": "航海桌面导航", "nu": 807037}], "day": "16", "month": "12"}, {"year": "2011", "data": [{"pv": 10026462, "vv": 1236730, "pid": "749c360516ebe533", "uv": 420494, "pname": "mobile优酷友情合作", "nu": 1236730}, {"pv": 17893920, "vv": 2373075, "pid": "749c360516ebe533", "uv": 533109, "pname": "3G门户G浏览器", "nu": 2373075}, {"pv": 29427041, "vv": 14269110, "pid": "749c360516ebe533", "uv": 276155, "pname": "百信手机网外链", "nu": 14269110}, {"pv": 7106385, "vv": 902434, "pid": "749c360516ebe533", "uv": 441599, "pname": "航海桌面导航", "nu": 902434}], "day": "17", "month": "12"}, {"year": "2011", "data": [{"pv": 10245069, "vv": 1289253, "pid": "749c360516ebe533", "uv": 428359, "pname": "mobile优酷友情合作", "nu": 1289253}, {"pv": 16366469, "vv": 2416836, "pid": "749c360516ebe533", "uv": 535023, "pname": "3G门户G浏览器", "nu": 2416836}, {"pv": 30343887, "vv": 14817690, "pid": "749c360516ebe533", "uv": 285791, "pname": "百信手机网外链", "nu": 14817690}, {"pv": 7162604, "vv": 903269, "pid": "749c360516ebe533", "uv": 451413, "pname": "航海桌面导航", "nu": 903269}], "day": "18", "month": "12"}, {"year": "2011", "data": [{"pv": 8928252, "vv": 1110394, "pid": "749c360516ebe533", "uv": 389020, "pname": "mobile优酷友情合作", "nu": 1110394}, {"pv": 12521422, "vv": 1880090, "pid": "749c360516ebe533", "uv": 448916, "pname": "3G门户G浏览器", "nu": 1880090}, {"pv": 26264948, "vv": 12763681, "pid": "749c360516ebe533", "uv": 248776, "pname": "百信手机网外链", "nu": 12763681}, {"pv": 6481151, "vv": 803660, "pid": "749c360516ebe533", "uv": 407620, "pname": "航海桌面导航", "nu": 803660}], "day": "19", "month": "12"}]}
        self.write({"status":"success", "items":all_data})
        self.finish()
        
        

class FactoryVideoAnalytics(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
    
    
    
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        _md5_ = _md5.hexdigest()
        m_value = mc.get(_md5.hexdigest()) or {}
        if settings.cache_on == 0:
            m_value = {}
            
        if not m_value:
    
    
    
            parnter_json = clientcache.getParnter()
            
            bt_sql = ""
            _btype = self.get_argument('btype','video').strip()
            if _btype == "video":
                bt_sql = "  2 "
            if _btype == "paike":
                bt_sql = "  4 "
            
            _fid = self.get_argument('fid', 'no').strip()
            
            
            _osid = self.get_argument('osid','no').strip()
            
            
            _type = self.get_argument('type','no').strip()
            _device = self.get_argument('device','no').strip()
            
            if _type == "phone":
                _type = 1
            if _type == "pad":
                _type = 2
            
            os_sql = ""
            os_order = " f_id "
            
            if _fid == "no":
                os_order = " f_id "
            elif _osid == "no":
                os_order = " os_id "
            elif _type == "no":
                os_order = " device_type "
            elif _device == "no":
                os_order = " pid "
                
            if _device != 'no':
                os_order = " pid "
            
            if _osid != "no":
                os_sql += " and os_id = %s " % _osid
            if _fid != "no":
                os_sql += " and f_id = %s " % _fid
            if _type != "no":
                os_sql += " and device_type = %s " % _type
            if _device != "no":
                c_device = []
                s_device = _device.split(",")
                for xc in s_device:
                    c_device.append("'"+str(xc)+"'")
                f_device = ",".join(c_device)
                os_sql += " and pid in (%s) " % f_device
                

            
            
            _staDate = self.get_argument('staDate', '2011/11/13').strip()
            _pd = self.get_argument('pd', '7').strip()
            
            if not _pd :
                _pd = 7
            else:
                _pd = int(_pd)
            
            if not _fid or not _osid :
                self.send_error(400, desc='invalid argument')
                #self.write({"status": "failed", "code": 400,  "desc": "invalid argument"})
                #self.finish()
                return
            
            st_time = ''
            et_time = ''
            
            if not _staDate:
                _time = datetime.datetime.now() + datetime.timedelta(days=-1)
                st_time = (_time + datetime.timedelta(days=-_pd)).strftime( '%Y%m%d')
                et_time = _time.strftime( '%Y%m%d')
            else :
                try:
                    #st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
                    _time = datetime.datetime.strptime(_staDate, '%Y/%m/%d')
                except :
                    self.send_error(400, desc='invalid argument')
                    #self.write({"status": "failed", "code": 400,  "desc": "invalid argument"})
                    #self.finish()
                    return
                st_time= _time.strftime( '%Y%m%d')
                et_time = (_time + datetime.timedelta(days=_pd)).strftime( '%Y%m%d')
            
            all_data = []
            results = {}
            os_data = []

            db = connectMySQL.connMySQL_stat()
            c=db.cursor()
                    
            if _fid == "no" or _osid == "no":
                sql = "SELECT date, sum(pv), sum(uv), sum(vv), sum(newuser), pid,os_id,device_type,f_id,business_type  FROM `stat_day_factory_collect` WHERE date>= '%s' and date < '%s' and partner_mode=1 and pid_stat=1  and ver = 'ALL' and prov = 'ALL' and city = 'ALL'  %s and business_type = %s  group by %s  " % (st_time, et_time, os_sql,bt_sql,os_order)    
            else:
                sql = "SELECT date, sum(pv), sum(uv), sum(vv), sum(newuser), pid,os_id,device_type,f_id,business_type  FROM `stat_day_factory_collect` WHERE date>= '%s' and date < '%s' and partner_mode=1 and pid_stat=1 and ver = 'ALL' and prov = 'ALL' and city = 'ALL'  %s and business_type = %s  group by date,%s " % (st_time, et_time, os_sql,bt_sql,os_order)
            
            #print sql
            
            
            sql = sql.encode('utf-8')
            print sql
            c.execute(sql)  
            res= c.fetchall()
            _tmpdate = ''
            print len(res)
            for x in res:
                date = str(x[0])
                pv = int(x[1])
                uv = int(x[2])
                vv = int(x[3])
                nu = int(x[4])
                pid = x[5]
                
                os = x[6]
                device_type = x[7]
                fid = x[8]
                type_2 = 1
                
                
                os = clientcache.getOsname(os)
                
                if device_type == 1:
                    device_type = "Phone"
                if device_type == 2:
                    device_type = "Pad"

                
                    
                if _fid == "no" or _osid == "no":
                    fname = clientcache.getFname(fid).strip()
                    if _fid == "no":
                        if fname != '':
                            all_data.insert(0,{'fid':fid,'pv':pv,'nu':nu,'uv':uv, 'vv':vv,'fname':fname})
                    elif _osid == "no":
                        if fname != '': 
                            all_data.insert(0,{'fid':fid,'pv':pv,'nu':nu,'uv':uv, 'vv':vv,'fname':fname,'os':os})
                    elif _type == "no":
                        if fname != '':
                            all_data.insert(0,{'fid':fid,'pv':pv,'nu':nu,'uv':uv, 'vv':vv,'fname':fname,'os':os,'type':device_type})
                    else:
                        if fname != '':
                            
                            
                            
                            all_data.insert(0,{'fid':fid,'pv':pv,'nu':nu,'uv':uv, 'vv':vv, 'type':device_type, 'os':os , 'fname':fname, 'device':parnter_json.get(pid,['',''])[1]})
                else:
                    
                    #print _tmpdate
                    
                    
                    
                    if _tmpdate and _tmpdate != date:
                        results['data'] = os_data
                        results['year'] = _tmpdate[:4]
                        results['month'] = _tmpdate[4:6]
                        results['day'] = _tmpdate[6:]
                        all_data.append(results)
                        results = {}
                        os_data = []
                    
                    fname = clientcache.getFname(fid).strip()
                    if _fid == "no":
                        if fname != '':
                            os_data.insert(0,{'fid':fid,'pv':pv,'nu':nu,'uv':uv, 'vv':vv,'fname':fname})
                    elif _osid == "no":
                        if fname != '': 
                            os_data.insert(0,{'fid':fid,'pv':pv,'nu':nu,'uv':uv, 'vv':vv,'fname':fname,'os':os})
                    elif _type == "no":
                        if fname != '':
                            os_data.insert(0,{'fid':fid,'pv':pv,'nu':nu,'uv':uv, 'vv':vv,'fname':fname,'os':os,'type':device_type})
                    else:
                        if fname != '':
                            
                            #print s_device
                            
                            
                            for v1 in s_device:
                                
                                
                                hc = os_data
                                yiyou = 0
                                if len(hc) > 0:
                                    for xy in xrange(len(hc)):
                                        if 'v1' in hc[xy]:
                                            yiyou = 1
                            
                                sql = "SELECT *  FROM `stat_day_factory_collect` WHERE date = '%s' and partner_mode=1 and pid_stat=1   and os_id = '%s'  and f_id = '%s'  and device_type = '%s'  and pid = '%s'  and ver = 'ALL' and prov = 'ALL' and city = 'ALL'  and business_type =   '%s' " % (x[0],x[6],x[8],x[7],v1,x[9])
                                #print sql
                                c.execute(sql)  
                                res = c.fetchone()
                                  
                                if (res == None):
                                    os_data.insert(0,{'fid':fid,'pv':0,'nu':0,'uv':0, 'vv':0, 'type':device_type, 'os':os , 'fname':fname, 'device':parnter_json.get(v1,['',''])[1],'v1':v1})
                                    
                                    
                                
                                
                            
                            os_data.insert(0,{'fid':fid,'pv':pv,'nu':nu,'uv':uv, 'vv':vv, 'type':device_type, 'os':os , 'fname':fname, 'device':parnter_json.get(pid,['',''])[1]})
                    _tmpdate = date
            
            c.close()
            db.close()
            #print len(os_data)
            
           
            if len(os_data) > 0 :
                results['data'] = os_data
                results['year'] = _tmpdate[:4]
                results['month'] = _tmpdate[4:6]
                results['day'] = _tmpdate[6:]
                all_data.append(results)
                results = {}
                os_data = []
            
            #print all_data
            try:
                mc.set(_md5_,all_data)
            except:
                pass
            
        else:
            all_data = m_value
        self.write({"status":"success", "items":all_data})
        self.finish()
        
class PromoVideoAnalytics(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
    
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        _md5_ = _md5.hexdigest()
        m_value = mc.get(_md5.hexdigest()) or {}
        if settings.cache_on == 0:
            m_value = {}
            
        if not m_value:
    
            
            parnter_json = clientcache.getParnter()
            
            
            bt_sql = ""
            _btype = self.get_argument('btype','video').strip()
            if _btype == "video":
                bt_sql = "  2 "
            if _btype == "paike":
                bt_sql = "  4 "
            
            _fid = self.get_argument('fid', 'no').strip()
            _osid = self.get_argument('osid','no').strip()
            
            
            _type = self.get_argument('type','no').strip()
            
            _ftype = self.get_argument('ftype',"8").strip()
            
            _fsql = ""
            
            if _ftype == "8":
                _fsql = " 8 "
            if _ftype == "2":
                _fsql = " 2 "
            
            _device = self.get_argument('device','no').strip()
            
            if _type == "phone":
                _type = 1
            if _type == "pad":
                _type = 2
            
            os_sql = ""
            os_order = " f_id "
            
            if _fid == "no":
                os_order = " f_id "
            elif _osid == "no":
                os_order = " os_id "
            elif _type == "no":
                os_order = " device_type "
            elif _device == "no":
                os_order = " pid "
                
            if _device != 'no':
                os_order = " pid "
            
            if _osid != "no":
                os_sql += " and os_id = %s " % _osid
            if _fid != "no":
                os_sql += " and f_id = %s " % _fid
            if _type != "no":
                os_sql += " and device_type = %s " % _type
            if _device != "no":
                c_device = []
                s_device = _device.split(",")
                for xc in s_device:
                    c_device.append("'"+str(xc)+"'")
                f_device = ",".join(c_device)
                os_sql += " and pid in (%s) " % f_device
                

            
            
            _staDate = self.get_argument('staDate', '2011/11/13').strip()
            _pd = self.get_argument('pd', '7').strip()
            
            if not _pd :
                _pd = 7
            else:
                _pd = int(_pd)
            
            if not _fid or not _osid :
                self.send_error(400, desc='invalid argument')
                #self.write({"status": "failed", "code": 400,  "desc": "invalid argument"})
                #self.finish()
                return
            
            st_time = ''
            et_time = ''
            
            if not _staDate:
                _time = datetime.datetime.now() + datetime.timedelta(days=-1)
                st_time = (_time + datetime.timedelta(days=-_pd)).strftime( '%Y%m%d')
                et_time = _time.strftime( '%Y%m%d')
            else :
                try:
                    #st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
                    _time = datetime.datetime.strptime(_staDate, '%Y/%m/%d')
                except :
                    self.send_error(400, desc='invalid argument')
                    #self.write({"status": "failed", "code": 400,  "desc": "invalid argument"})
                    #self.finish()
                    return
                st_time= _time.strftime( '%Y%m%d')
                et_time = (_time + datetime.timedelta(days=_pd)).strftime( '%Y%m%d')
            
            all_data = []
            results = {}
            os_data = []

            db = connectMySQL.connMySQL_stat()
            c=db.cursor()        
            
            if _fid == "no" or _osid == "no":
                sql = "SELECT date, sum(pv), sum(uv), sum(vv), sum(newuser), pid,os_id,device_type,f_id,partner_mode,business_type  FROM `stat_day_channel_collect` WHERE date>= '%s' and date < '%s' and partner_mode = %s and pid_stat=1  %s and ver = 'ALL' and prov = 'ALL' and city = 'ALL'  and business_type = %s  group by %s " % (st_time, et_time,_fsql,os_sql,bt_sql,os_order)    
            else:
                sql = "SELECT date, sum(pv), sum(uv), sum(vv), sum(newuser), pid,os_id,device_type,f_id,partner_mode,business_type  FROM `stat_day_channel_collect` WHERE date>= '%s' and date < '%s' and partner_mode = %s and pid_stat=1  %s and ver = 'ALL' and prov = 'ALL' and city = 'ALL'  and business_type = %s  group by date,%s " % (st_time, et_time,_fsql,os_sql,bt_sql,os_order)
            
            
            #sql = "SELECT date, pv, uv, vv, newuser, pid,os_id,device_type,f_id,partner_mode  FROM `stat_day_factory` WHERE date>= '%s' and date < '%s' and partner_mode = %s and pid_stat=1  %s  group by date,%s " % (st_time, et_time,_fsql,os_sql,os_order)
            
            
            
            print sql
            #print '123'
            logging.info(sql)
            c.execute(sql)  
            res= c.fetchall()
            _tmpdate = ''
            print len(res)
            for x in res:
                date = str(x[0])
                pv = int(x[1])
                uv = int(x[2])
                vv = int(x[3])
                nu = int(x[4])
                pid = x[5]
                
                os = x[6]
                device_type = x[7]
                fid = x[8]
                
                os = clientcache.getOsname(os)
                
                
                if x[9] == 8:
                    type_2 = 8
                if x[9] == 2:
                    type_2 = 2
                
                if device_type == 1:
                    device_type = "Phone"
                if device_type == 2:
                    device_type = "Pad"

                
                    
                if _fid == "no" or _osid == "no":
                    fname = clientcache.getFname(fid).strip()
                    if _fid == "no":
                        if fname != '':
                            all_data.insert(0,{'fid':fid,'pv':pv,'nu':nu,'uv':uv, 'vv':vv,'fname':fname,'ftype':type_2})
                    elif _osid == "no":
                        if fname != '': 
                            all_data.insert(0,{'fid':fid,'pv':pv,'nu':nu,'uv':uv, 'vv':vv,'fname':fname,'os':os,'ftype':type_2})
                    elif _type == "no":
                        if fname != '':
                            all_data.insert(0,{'fid':fid,'pv':pv,'nu':nu,'uv':uv, 'vv':vv,'fname':fname,'os':os,'type':device_type,'ftype':type_2})
                    else:
                        if fname != '':
                            
                            
                            """for v1 in s_device:
                            
                                sql = "SELECT *  FROM `stat_day_channel` WHERE date = '%s' and partner_mode= '%s' and pid_stat=1   and os_id = '%s'  and f_id = '%s'  and device_type = '%s'  and pid = '%s'  and business_type =   '%s' " % (x[0],x[9],x[6],x[8],x[7],v1,x[10])
                                
                                logging.info(sql)
                                c.execute(sql)  
                                res = c.fetchone()
                    
                                if res == None:
                                    os_data.insert(0,{'fid':fid,'pv':0,'nu':0,'uv':0, 'vv':0, 'type':device_type, 'os':os , 'fname':fname, 'device':parnter_json.get(v1,['',''])[1],'ftype':type_2})"""
                            
                            all_data.insert(0,{'fid':fid,'pv':pv,'nu':nu,'uv':uv, 'vv':vv, 'type':device_type, 'os':os , 'fname':fname, 'device':parnter_json.get(pid,['',''])[1],'ftype':type_2})
                else:
                    if _tmpdate and _tmpdate != date:
                        results['data'] = os_data
                        results['year'] = _tmpdate[:4]
                        results['month'] = _tmpdate[4:6]
                        results['day'] = _tmpdate[6:]
                        all_data.append(results)
                        results = {}
                        os_data = []
                    
               
                    fname = clientcache.getFname(fid).strip()
                    if _fid == "no":
                        if fname != '':
                            os_data.insert(0,{'fid':fid,'pv':pv,'nu':nu,'uv':uv, 'vv':vv,'fname':fname,'ftype':type_2})
                    elif _osid == "no":
                        if fname != '': 
                            os_data.insert(0,{'fid':fid,'pv':pv,'nu':nu,'uv':uv, 'vv':vv,'fname':fname,'os':os,'ftype':type_2})
                    elif _type == "no":
                        if fname != '':
                            os_data.insert(0,{'fid':fid,'pv':pv,'nu':nu,'uv':uv, 'vv':vv,'fname':fname,'os':os,'type':device_type,'ftype':type_2})
                    else:
                        if fname != '':
                            
                            """for v1 in s_device:
                            
                                sql = "SELECT *  FROM `stat_day_channel` WHERE date = '%s' and partner_mode= '%s' and pid_stat=1   and os_id = '%s'  and f_id = '%s'  and device_type = '%s'  and pid = '%s'  and business_type =   '%s' " % (x[0],x[9],x[6],x[8],x[7],v1,x[10])
                                
                                logging.info(sql)
                                c.execute(sql)  
                                res = c.fetchone()
                    
                                if res == None:
                                    os_data.insert(0,{'fid':fid,'pv':0,'nu':0,'uv':0, 'vv':0, 'type':device_type, 'os':os , 'fname':fname, 'device':parnter_json.get(v1,['',''])[1],'ftype':type_2})"""
                            
                            
                            os_data.insert(0,{'fid':fid,'pv':pv,'nu':nu,'uv':uv, 'vv':vv, 'type':device_type, 'os':os , 'fname':fname, 'device':parnter_json.get(pid,['',''])[1],'ftype':type_2})
                
                    _tmpdate = date
            
            c.close()
            db.close()
            #print len(os_data)
            if len(os_data) > 0 :
                results['data'] = os_data
                results['year'] = _tmpdate[:4]
                results['month'] = _tmpdate[4:6]
                results['day'] = _tmpdate[6:]
                all_data.append(results)
            try:
                mc.set(_md5_,all_data)
            except:
                pass
        else:
            all_data = m_value
        self.write({"status":"success", "items":all_data})
        self.finish()
        



class MainDlVideo(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
    
    
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        _md5_ = _md5.hexdigest()
        m_value = mc.get(_md5.hexdigest()) or {}
        if settings.cache_on == 0:
            m_value = {}
            
        if not m_value:
        
        
            table_name = "stat_store_download_update"
            
            pidtype_json = clientcache.getPidType()
            
            _time = self.get_argument('staDate', '2011/11/13').strip()
            _pd = self.get_argument('pd','').strip()
            
            
            try:
                st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                #self.write({"status": "failed", "code": 400,  "desc": "invalid argument"})
                #self.finish()
                return
            
            if not _pd:
                ed_time = datetime.datetime.now()
                delta = ed_time - st_time 
                _pd =  abs(delta.days)
            _pd = int(_pd)
            et_time = st_time + datetime.timedelta(days=_pd)
            st_datestr = st_time.strftime('%Y%m%d')
            et_datestr = et_time.strftime('%Y%m%d')
            
            all_data = []
            results = {}
            os_data = []
            
            db = connectMySQL.connMySQL_stat()
            c=db.cursor()

            sql = "SELECT date, sum(download_num),sum(update_num),device_id FROM `stat_store_download_update` WHERE date>= '{0}' and date < '{1}'  and app_type = 1   group by date, device_id ".format(st_datestr, et_datestr)
            logging.info(sql)
            print sql
            c.execute(sql)  
            res= c.fetchall()
            _tmpdate = ''
            
            
            
            for x in res:
                date = str(x[0])
                os = int(x[3])
                download_num = int(x[1])
                update_num = int(x[2])
                
                
                if _tmpdate and _tmpdate != date:
                    results['data'] = os_data
                    results['year'] = _tmpdate[:4]
                    results['month'] = _tmpdate[4:6]
                    results['day'] = _tmpdate[6:]
                    all_data.append(results)
                    results = {}
                    os_data = []
                
                if(os == 1):
                    os = "Phone"
                else:
                    os = "Pad"
                
                
                sql = "SELECT device_id FROM `stat_store_download_update` WHERE date = '%s'  and app_type = 1 and device_id = 1; " % x[0]
                logging.info(sql)
                c.execute(sql)  
                res = c.fetchone()
                
                if res == None:
                    os_data.insert(0,{'type':'Phone', 'downloadnum':0, 'updatenum':0})
                    
                sql = "SELECT device_id FROM `stat_store_download_update` WHERE date = '%s'  and app_type = 1 and device_id = 2; " % x[0]
                logging.info(sql)
                c.execute(sql)  
                res = c.fetchone()
                
                if res == None:
                    os_data.insert(0,{'type':'Pad', 'downloadnum':0, 'updatenum':0})
                
                
                os_data.insert(0,{'type':os, 'downloadnum':download_num, 'updatenum':update_num})
                
                         
                _tmpdate = date
            
            if len(os_data) > 0 :
                results['data'] = os_data
                results['year'] = _tmpdate[:4]
                results['month'] = _tmpdate[4:6]
                results['day'] = _tmpdate[6:]
                all_data.append(results)
                results = {}
                os_data = []
            
            c.close()
            db.close()
            try:
                mc.set(_md5_,all_data)
            except:
                pass
            
        else:
            all_data = m_value
        
        self.write({"status":"success", "items":all_data})
        self.finish()
        
        

class MainBoardVideo(BaseHandler):
    def get(self): 
    
        import sys 
        reload(sys) 
        sys.setdefaultencoding('utf8')
        
        
        table_name = "stat_store_board"
        
        pidtype_json = clientcache.getPidType()
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        
        shuliang = self.get_argument('shuliang','200').strip()
        pindao = self.get_argument('pindao','1').strip()
        _type = self.get_argument('type','1').strip()
        
        
        
        
        pindaosql = ""
        
        if _type == "1":
        
            if pindao == "1":
                pindaosql = "%s" % "5"
            else:
                pindaosql = "%s" % "1"
        elif _type == "2":
        
            if pindao == "1":
                pindaosql = "%s" % "2"
            else:
                pindaosql = "%s" % "3"
        
        try:
            st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
        except :
            self.send_error(400, desc='invalid argument')
            #self.write({"status": "failed", "code": 400,  "desc": "invalid argument"})
            #self.finish()
            return
        
        if not _pd:
            ed_time = datetime.datetime.now()
            delta = ed_time - st_time 
            _pd =  abs(delta.days)
        _pd = int(_pd)
        et_time = st_time + datetime.timedelta(days=_pd)
        st_datestr = st_time.strftime('%Y%m%d')
        et_datestr = et_time.strftime('%Y%m%d')
        
        all_data = []
        results = {}
        os_data = []
        
        db = connectMySQL.connMySQL_stat()
        c=db.cursor()

        sql = " SELECT app_rank,app_name,board_type,device_id,app_logo,app_id FROM `stat_store_board` where device_id = '%s' and board_type = '%s' and date = '%s' order by app_rank asc limit %s  " % (_type,pindaosql,st_datestr,shuliang)
        
        print sql
        
        
        logging.info(sql)
        c.execute(sql)  
        res= c.fetchall()
        
        
        fanhui = ""
        youku = ""
        jishu = 0
        for x in res:
            app_rank = x[0]
            app_name = x[1]
            board_type = x[2]
            app_logo = x[4]
            app_id = str(x[5])
            
            
            #print app_name
            
            bgc=''
            name_c=''
            app_name = app_name.strip()
            if app_id == '492031078' or app_id == '336141475' or app_id == '394075284':
                bgc = "background:#FFFF00;"
                name_c = " id = 'youkude' "
                youku = "<tr class='new_silver_even' ><td style='text-align:center;background:#FFFF00;'>%s</td><td class=\"\" style=\"text-align:left;padding-left:50px;background:#FFFF00;\"><img width=50 height=50 src='http://10.103.13.15:8000/static/img/%s'/>&nbsp;%s</td></tr>" % (app_rank,app_logo,app_name)
            
            if jishu % 2 == 0:
                fanhui+="<tr  class='new_silver_even'><td class=\"new_silver_first_n\" style='text-align:center;%s'>%s</td><td class=\"\" style=\"text-align:left;padding-left:50px;%s\"><img width=50 height=50 src='http://10.103.13.15:8000/static/img/%s'/>&nbsp;%s<div %s></div></td></tr>" % (bgc,app_rank,bgc,app_logo,app_name,name_c)
            else:
                fanhui+="<tr  class='new_silver_odd'><td class=\"new_silver_first_n\" style='text-align:center;%s'>%s</td><td class=\"\" style=\"text-align:left;padding-left:50px;%s\"><img width=50 height=50 src='http://10.103.13.15:8000/static/img/%s'/>&nbsp;%s<div %s></div></td></tr>" % (bgc,app_rank,bgc,app_logo,app_name,name_c)
            #print jishu
            jishu = jishu + 1
            
            
            
            
        
        c.close()
        db.close()
        
        fanhui = "%s%s" % (youku,fanhui)
        self.write(fanhui)
        self.finish()
        
        
class VidBoard(BaseHandler):
    def get(self): 
    

        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        
        _type = self.get_argument('dt','1,2').strip()
        _os_id = self.get_argument('os','61,52,59').strip()
        
        
        try:
            st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
        except :
            self.send_error(400, desc='invalid argument')
            return
        
        if not _pd:
            ed_time = datetime.datetime.now()
            delta = ed_time - st_time 
            _pd =  abs(delta.days)
        _pd = int(_pd)
        et_time = st_time + datetime.timedelta(days=_pd)
        st_datestr = st_time.strftime('%Y%m%d')
        et_datestr = et_time.strftime('%Y%m%d')
        

        
        db = connectMySQL.connMySQL_stat()
        c=db.cursor()

        sql = u" SELECT sum(a.playtimes),a.vid,coalesce(b.videoname,'未知'),coalesce(b.videotype,'未知') FROM `stat_vid_board` a left join `stat_vid_dict` b on a.vid = b.vid  where a.os_id in (%s) and a.device_type in (%s) and a.date = '%s' and a.vid != '' and a.vid != 'null' group by a.vid order by sum(a.playtimes) desc limit 500  " % (_os_id,_type,st_datestr)
        sql = sql.encode('utf-8')
        print sql
        c.execute(sql)  
        res= c.fetchall()
        
        day_table = ""
        jishu = 1
        for x in res:
            playtimes = x[0]
            vid = x[1]
            vname = x[2]
            vtype = x[3]
            
            if vname == "":
                vname = u"未知"
            if vtype == "":
                vtype = u"未知"
            
            #print vname.encode('utf-8')
            
            
            if jishu % 2 == 0:
                day_table+="<tr  class='new_silver_even'><td class=\"new_silver_first_n\" style='text-align:center;'>%s</td><td class=\"\" style=\"text-align:left;\">%s</td><td class=\"\" style=\"text-align:left;\">%s</td><td class=\"\" style=\"text-align:right;\">%s</td></tr>" % (jishu,vname,vtype,cnsort.num2money(playtimes))
            else:
                day_table+="<tr  class='new_silver_odd'><td class=\"new_silver_first_n\" style='text-align:center;'>%s</td><td class=\"\" style=\"text-align:left;\">%s</td><td class=\"\" style=\"text-align:left;\">%s</td><td class=\"\" style=\"text-align:right;\">%s</td></tr>" % (jishu,vname,vtype,cnsort.num2money(playtimes))
            jishu = jishu + 1
        
        zhou_st_datestr = st_datestr
        
        riqis = str(zhou_st_datestr)
        #print riqis
        
        zhou_now = datetime.datetime.strptime(riqis,'%Y%m%d')
        _pickday = zhou_now.weekday()
        
        
                
        yy = riqis[0:4]
        mm = riqis[4:6]
        dd = riqis[6:]
        from datetime import date
        from datetime import timedelta
        start = date(year=int(yy),month=int(mm),day=int(dd))
        if _pickday != 6:
            start_day = start - timedelta(days=start.weekday()) + timedelta(days=0, weeks=-1)
            end_day = start - timedelta(days=start.weekday()) + timedelta(days=6, weeks=-1)
        else:
            start_day = start - timedelta(days=start.weekday()) + timedelta(days=0, weeks=0)
            end_day = start - timedelta(days=start.weekday()) + timedelta(days=6, weeks=0)
        
        
        start_day = start_day.strftime('%Y%m%d')
        end_day = end_day.strftime('%Y%m%d')
        
        #周排名开始
        sql = u" SELECT sum(a.playtimes),a.vid,coalesce(b.videoname,'未知'),coalesce(b.videotype,'未知') FROM `stat_vid_board_week` a left join `stat_vid_dict` b on a.vid = b.vid  where a.os_id in (%s) and a.device_type in (%s) and a.start_date = %s and a.end_date = %s and a.vid != '' and a.vid != 'null' group by a.vid order by sum(a.playtimes) desc limit 500  " % (_os_id,_type,start_day,end_day)
        sql = sql.encode('utf-8')
        print sql
        c.execute(sql)  
        res= c.fetchall()
        
        
        week_table = ""
        jishu = 1
        for x in res:
            playtimes = x[0]
            vid = x[1]
            vname = x[2]
            vtype = x[3]
            
            if vname == "":
                vname = u"未知"
            if vtype == "":
                vtype = u"未知"
            
            #print vname.encode('utf-8')
            
            
            if jishu % 2 == 0:
                week_table+="<tr  class='new_silver_even'><td class=\"new_silver_first_n\" style='text-align:center;'>%s</td><td class=\"\" style=\"text-align:left;\">%s</td><td class=\"\" style=\"text-align:left;\">%s</td><td class=\"\" style=\"text-align:right;\">%s</td></tr>" % (jishu,vname,vtype,cnsort.num2money(playtimes))
            else:
                week_table+="<tr  class='new_silver_odd'><td class=\"new_silver_first_n\" style='text-align:center;'>%s</td><td class=\"\" style=\"text-align:left;\">%s</td><td class=\"\" style=\"text-align:left;\">%s</td><td class=\"\" style=\"text-align:right;\">%s</td></tr>" % (jishu,vname,vtype,cnsort.num2money(playtimes))
            jishu = jishu + 1
            
        c.close()
        db.close()
        fanhui = {}
        fanhui['daytime'] = "(%s)" % (cnsort.fordate(st_datestr,1))
        fanhui['weektime'] = "(%s-%s)" % (cnsort.fordate(start_day,1),cnsort.fordate(end_day,1))
        fanhui['day'] = day_table
        fanhui['week'] = week_table
        
        self.write(fanhui)
        self.finish()
        
        
        
class PhVideo(BaseHandler):
    def get(self): 
    

        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        
        _type = self.get_argument('dt','-1').strip()
        _os_id = self.get_argument('os','-1').strip()
        
        
        try:
            st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
        except :
            self.send_error(400, desc='invalid argument')
            return
        
        if not _pd:
            ed_time = datetime.datetime.now()
            delta = ed_time - st_time 
            _pd =  abs(delta.days)
        _pd = int(_pd)
        et_time = st_time + datetime.timedelta(days=_pd)
        st_datestr = st_time.strftime('%Y%m%d')
        et_datestr = et_time.strftime('%Y%m%d')
        

        
        db = connectMySQL.connMySQL_stat()
        c=db.cursor()

        sql = u" SELECT uv,ph,brand FROM `stat_ph_day`  where date = %s and os_id = %s and device_type = %s   and business_type = 2       order by uv desc  " % (st_datestr,_os_id,_type)
        sql = sql.encode('utf-8')
        print sql
        c.execute(sql)  
        res= c.fetchall()
        day_uvall = 0
        for x in res:
            uv = int(x[0])
            day_uvall += uv
        
        day_table = ""
        jishu = 1
        for x in res:
            
            if jishu <= 50:
            
                uv = int(x[0])
                ph = str(x[1])
                
                
                if jishu % 2 == 0:
                    class_c = "new_silver_even"
                else:
                    class_c = "new_silver_odd"
                    
                
                try:
                    _now = uv / day_uvall
                except:
                    _now = 0
                _now = round(_now,4)
                nl = str(_now).split(".")
                if len(str(nl[1])) < 4:
                    zhanbi = "%s0%s" % (_now * 100,"%")
                else:
                    zhanbi = "%s%s" % (_now * 100,"%")
                    
                
                day_table+="<tr  class='%s'><td class=\"new_silver_first_n\" style='text-align:center;'>%s</td><td class=\"\" style=\"text-align:left;\">%s</td><td class=\"\" style=\"text-align:left;\">%s</td><td class=\"\" style=\"text-align:left;\">%s</td><td class=\"\" style=\"text-align:right;\">%s</td></tr>" % (class_c,jishu,ph,str(x[2]),uv,zhanbi)

            jishu = jishu + 1
        
        
        zhou_st_datestr = st_datestr
        riqis = str(zhou_st_datestr)
        zhou_now = datetime.datetime.strptime(riqis,'%Y%m%d')
        _pickday = zhou_now.weekday()
        
        yy = riqis[0:4]
        mm = riqis[4:6]
        dd = riqis[6:]
        from datetime import date
        from datetime import timedelta
        start = date(year=int(yy),month=int(mm),day=int(dd))
        if _pickday != 6:
            start_day = start - timedelta(days=start.weekday()) + timedelta(days=0, weeks=-1)
            end_day = start - timedelta(days=start.weekday()) + timedelta(days=6, weeks=-1)
        else:
            start_day = start - timedelta(days=start.weekday()) + timedelta(days=0, weeks=0)
            end_day = start - timedelta(days=start.weekday()) + timedelta(days=6, weeks=0)
        
        
        start_day = start_day.strftime('%Y%m%d')
        end_day = end_day.strftime('%Y%m%d')
        
        #周排名开始
        sql = u" SELECT uv,ph,brand FROM `stat_ph_week`  where start_date = %s and os_id = %s and device_type = %s   and business_type = 2  order by uv desc   " % (start_day,_os_id,_type)
        sql = sql.encode('utf-8')
        print sql
        c.execute(sql)  
        res= c.fetchall()
        
        week_uvall = 0
        for x in res:
            uv = int(x[0])
            week_uvall += uv
        
        week_table = ""
        jishu = 1
        for x in res:
            
            if jishu <= 50:
            
                uv = int(x[0])
                ph = str(x[1])
                
                
                if jishu % 2 == 0:
                    class_c = "new_silver_even"
                else:
                    class_c = "new_silver_odd"
                    
                
                try:
                    _now = uv / week_uvall
                except:
                    _now = 0
                _now = round(_now,4)
                nl = str(_now).split(".")
                if len(str(nl[1])) < 4:
                    zhanbi = "%s0%s" % (_now * 100,"%")
                else:
                    zhanbi = "%s%s" % (_now * 100,"%")
                    
                
                week_table+="<tr  class='%s'><td class=\"new_silver_first_n\" style='text-align:center;'>%s</td><td class=\"\" style=\"text-align:left;\">%s</td><td class=\"\" style=\"text-align:left;\">%s</td><td class=\"\" style=\"text-align:left;\">%s</td><td class=\"\" style=\"text-align:right;\">%s</td></tr>" % (class_c,jishu,ph,str(x[2]),uv,zhanbi)
            jishu = jishu + 1
            
        
        
        
        today = datetime.datetime.strptime(st_datestr,'%Y%m%d')
        first = datetime.date(day=1, month=today.month, year=today.year)
        lastMonth = first - datetime.timedelta(days=1)
        start_md = lastMonth.strftime("%Y%m01")
        
        #月排名开始
        sql = u" SELECT uv,ph,brand FROM `stat_ph_month`  where start_date = %s and os_id = %s and device_type = %s   and business_type = 2 order by uv desc   " % (start_md,_os_id,_type)
        sql = sql.encode('utf-8')
        print sql
        c.execute(sql)  
        res= c.fetchall()
        
        month_uvall = 0
        for x in res:
            uv = int(x[0])
            month_uvall += uv
        
        month_table = ""
        jishu = 1
        for x in res:
            if jishu <= 50:
                uv = int(x[0])
                ph = str(x[1])
                
                
                if jishu % 2 == 0:
                    class_c = "new_silver_even"
                else:
                    class_c = "new_silver_odd"
                    
                
                try:
                    _now = uv / month_uvall
                except:
                    _now = 0
                _now = round(_now,4)
                nl = str(_now).split(".")
                if len(str(nl[1])) < 4:
                    zhanbi = "%s0%s" % (_now * 100,"%")
                else:
                    zhanbi = "%s%s" % (_now * 100,"%")
                    
                
                month_table+="<tr  class='%s'><td class=\"new_silver_first_n\" style='text-align:center;'>%s</td><td class=\"\" style=\"text-align:left;\">%s</td><td class=\"\" style=\"text-align:left;\">%s</td><td class=\"\" style=\"text-align:left;\">%s</td><td class=\"\" style=\"text-align:right;\">%s</td></tr>" % (class_c,jishu,ph,str(x[2]),uv,zhanbi)
            jishu = jishu + 1
        
        
            
        c.close()
        db.close()
        fanhui = {}
        fanhui['daytime'] = "(%s)" % (cnsort.fordate(st_datestr,1))
        fanhui['weektime'] = "(%s-%s)" % (cnsort.fordate(start_day,1),cnsort.fordate(end_day,1))
        fanhui['day'] = day_table
        fanhui['week'] = week_table
        fanhui['month'] = month_table
        
        self.write(fanhui)
        self.finish()
        



        
class PhPaike(BaseHandler):
    def get(self): 
    

        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        
        _type = self.get_argument('dt','-1').strip()
        _os_id = self.get_argument('os','-1').strip()
        
        
        try:
            st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
        except :
            self.send_error(400, desc='invalid argument')
            return
        
        if not _pd:
            ed_time = datetime.datetime.now()
            delta = ed_time - st_time 
            _pd =  abs(delta.days)
        _pd = int(_pd)
        et_time = st_time + datetime.timedelta(days=_pd)
        st_datestr = st_time.strftime('%Y%m%d')
        et_datestr = et_time.strftime('%Y%m%d')
        

        
        db = connectMySQL.connMySQL_stat()
        c=db.cursor()

        sql = u" SELECT uv,ph,brand FROM `stat_ph_day`  where date = %s and os_id = %s and device_type = %s   and business_type = 4       order by uv desc  " % (st_datestr,_os_id,_type)
        sql = sql.encode('utf-8')
        print sql
        c.execute(sql)  
        res= c.fetchall()
        day_uvall = 0
        for x in res:
            uv = int(x[0])
            day_uvall += uv
        
        day_table = ""
        jishu = 1
        for x in res:
            
            if jishu <= 50:
            
                uv = int(x[0])
                ph = str(x[1])
                
                
                if jishu % 2 == 0:
                    class_c = "new_silver_even"
                else:
                    class_c = "new_silver_odd"
                    
                
                try:
                    _now = uv / day_uvall
                except:
                    _now = 0
                _now = round(_now,4)
                nl = str(_now).split(".")
                if len(str(nl[1])) < 4:
                    zhanbi = "%s0%s" % (_now * 100,"%")
                else:
                    zhanbi = "%s%s" % (_now * 100,"%")
                    
                
                day_table+="<tr  class='%s'><td class=\"new_silver_first_n\" style='text-align:center;'>%s</td><td class=\"\" style=\"text-align:left;\">%s</td><td class=\"\" style=\"text-align:left;\">%s</td><td class=\"\" style=\"text-align:left;\">%s</td><td class=\"\" style=\"text-align:right;\">%s</td></tr>" % (class_c,jishu,ph,str(x[2]),uv,zhanbi)

            jishu = jishu + 1
        
        
        zhou_st_datestr = st_datestr
        riqis = str(zhou_st_datestr)
        zhou_now = datetime.datetime.strptime(riqis,'%Y%m%d')
        _pickday = zhou_now.weekday()
        
        yy = riqis[0:4]
        mm = riqis[4:6]
        dd = riqis[6:]
        from datetime import date
        from datetime import timedelta
        start = date(year=int(yy),month=int(mm),day=int(dd))
        if _pickday != 6:
            start_day = start - timedelta(days=start.weekday()) + timedelta(days=0, weeks=-1)
            end_day = start - timedelta(days=start.weekday()) + timedelta(days=6, weeks=-1)
        else:
            start_day = start - timedelta(days=start.weekday()) + timedelta(days=0, weeks=0)
            end_day = start - timedelta(days=start.weekday()) + timedelta(days=6, weeks=0)
        
        
        start_day = start_day.strftime('%Y%m%d')
        end_day = end_day.strftime('%Y%m%d')
        
        #周排名开始
        sql = u" SELECT uv,ph,brand FROM `stat_ph_week`  where start_date = %s and os_id = %s and device_type = %s   and business_type = 4  order by uv desc   " % (start_day,_os_id,_type)
        sql = sql.encode('utf-8')
        print sql
        c.execute(sql)  
        res= c.fetchall()
        
        week_uvall = 0
        for x in res:
            uv = int(x[0])
            week_uvall += uv
        
        week_table = ""
        jishu = 1
        for x in res:
            
            if jishu <= 50:
            
                uv = int(x[0])
                ph = str(x[1])
                
                
                if jishu % 2 == 0:
                    class_c = "new_silver_even"
                else:
                    class_c = "new_silver_odd"
                    
                
                try:
                    _now = uv / week_uvall
                except:
                    _now = 0
                _now = round(_now,4)
                nl = str(_now).split(".")
                if len(str(nl[1])) < 4:
                    zhanbi = "%s0%s" % (_now * 100,"%")
                else:
                    zhanbi = "%s%s" % (_now * 100,"%")
                    
                
                week_table+="<tr  class='%s'><td class=\"new_silver_first_n\" style='text-align:center;'>%s</td><td class=\"\" style=\"text-align:left;\">%s</td><td class=\"\" style=\"text-align:left;\">%s</td><td class=\"\" style=\"text-align:left;\">%s</td><td class=\"\" style=\"text-align:right;\">%s</td></tr>" % (class_c,jishu,ph,str(x[2]),uv,zhanbi)
            jishu = jishu + 1
            
        
        
        
        today = datetime.datetime.strptime(st_datestr,'%Y%m%d')
        first = datetime.date(day=1, month=today.month, year=today.year)
        lastMonth = first - datetime.timedelta(days=1)
        start_md = lastMonth.strftime("%Y%m01")
        
        #月排名开始
        sql = u" SELECT uv,ph,brand FROM `stat_ph_month`  where start_date = %s and os_id = %s and device_type = %s   and business_type = 4 order by uv desc   " % (start_md,_os_id,_type)
        sql = sql.encode('utf-8')
        print sql
        c.execute(sql)  
        res= c.fetchall()
        
        month_uvall = 0
        for x in res:
            uv = int(x[0])
            month_uvall += uv
        
        month_table = ""
        jishu = 1
        for x in res:
            if jishu <= 50:
                uv = int(x[0])
                ph = str(x[1])
                
                
                if jishu % 2 == 0:
                    class_c = "new_silver_even"
                else:
                    class_c = "new_silver_odd"
                    
                
                try:
                    _now = uv / month_uvall
                except:
                    _now = 0
                _now = round(_now,4)
                nl = str(_now).split(".")
                if len(str(nl[1])) < 4:
                    zhanbi = "%s0%s" % (_now * 100,"%")
                else:
                    zhanbi = "%s%s" % (_now * 100,"%")
                    
                
                month_table+="<tr  class='%s'><td class=\"new_silver_first_n\" style='text-align:center;'>%s</td><td class=\"\" style=\"text-align:left;\">%s</td><td class=\"\" style=\"text-align:left;\">%s</td><td class=\"\" style=\"text-align:left;\">%s</td><td class=\"\" style=\"text-align:right;\">%s</td></tr>" % (class_c,jishu,ph,str(x[2]),uv,zhanbi)
            jishu = jishu + 1
        
        
            
        c.close()
        db.close()
        fanhui = {}
        fanhui['daytime'] = "(%s)" % (cnsort.fordate(st_datestr,1))
        fanhui['weektime'] = "(%s-%s)" % (cnsort.fordate(start_day,1),cnsort.fordate(end_day,1))
        fanhui['day'] = day_table
        fanhui['week'] = week_table
        fanhui['month'] = month_table
        
        self.write(fanhui)
        self.finish()
        
        


class MainBoardPaike(BaseHandler):
    def get(self): 
    
        import sys 
        reload(sys) 
        sys.setdefaultencoding('utf8')
        
        
        table_name = "stat_store_board"
        
        pidtype_json = clientcache.getPidType()
        
        _time = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd','').strip()
        
        shuliang = self.get_argument('shuliang','200').strip()
        pindao = self.get_argument('pindao','1').strip()
        _type = self.get_argument('type','1').strip()
        
        
        
        
        pindaosql = ""
        
        if _type == "1":
        
            if pindao == "1":
                pindaosql = "%s" % "5"
            else:
                pindaosql = "%s" % "4"
        elif _type == "2":
        
            if pindao == "1":
                pindaosql = "%s" % "2"
            else:
                pindaosql = "%s" % "6"
        
        try:
            st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
        except :
            self.send_error(400, desc='invalid argument')
            #self.write({"status": "failed", "code": 400,  "desc": "invalid argument"})
            #self.finish()
            return
        
        if not _pd:
            ed_time = datetime.datetime.now()
            delta = ed_time - st_time 
            _pd =  abs(delta.days)
        _pd = int(_pd)
        et_time = st_time + datetime.timedelta(days=_pd)
        st_datestr = st_time.strftime('%Y%m%d')
        et_datestr = et_time.strftime('%Y%m%d')
        
        all_data = []
        results = {}
        os_data = []
        
        db = connectMySQL.connMySQL_stat()
        c=db.cursor()

        sql = " SELECT app_rank,app_name,board_type,device_id,app_logo,app_id FROM `stat_store_board` where device_id = '%s' and board_type = '%s' and date = '%s' order by app_rank asc limit %s  " % (_type,pindaosql,st_datestr,shuliang)
        
        print sql
        
        
        logging.info(sql)
        c.execute(sql)  
        res= c.fetchall()
        
        
        fanhui = ""
        youku = ""
        
        jishu = 0
        for x in res:
            app_rank = x[0]
            app_name = x[1]
            board_type = x[2]
            app_logo = x[4]
            app_id = str(x[5])
            
            bgc=''
            app_name = app_name.strip()
            if app_id == '492031078' or app_id == '336141475' or app_id == '394075284':
                bgc = "background:#FFFF00;"
                youku = "<tr class='new_silver_even' ><td style='text-align:center;background:#FFFF00;'>%s</td><td class=\"\" style=\"text-align:left;padding-left:50px;background:#FFFF00;\"><img width=50 height=50 src='http://10.103.13.15:8000/static/img/%s'/>&nbsp;%s</td></tr>" % (app_rank,app_logo,app_name)
            
            if jishu % 2 == 0:
                fanhui+="<tr class='new_silver_even'><td class=\"new_silver_first_n\" style='text-align:center;%s'>%s</td><td class=\"\" style=\"text-align:left;padding-left:50px;%s\"><img width=50 height=50 src='http://10.103.13.15:8000/static/img/%s'/>&nbsp;%s</td></tr>" % (bgc,app_rank,bgc,app_logo,app_name)
            else:
                fanhui+="<tr class='new_silver_odd'><td class=\"new_silver_first_n\" style='text-align:center;%s'>%s</td><td class=\"\" style=\"text-align:left;padding-left:50px;%s\"><img width=50 height=50 src='http://10.103.13.15:8000/static/img/%s'/>&nbsp;%s</td></tr>" % (bgc,app_rank,bgc,app_logo,app_name)
            #print jishu
            jishu = jishu + 1
            
            
        
        c.close()
        db.close()
        fanhui = "%s%s" % (youku,fanhui)
        self.write(fanhui)
        self.finish()
        


class ReturnVersion(BaseHandler):    
    
    def get(self):         
        mysql_config = settings.mysql_cms_config
        d = {'"':'\\"', "'":"\\'", "\0":"\\\0", "\\":"\\\\"}      
        dbMysql = MySQLdb.connect(**mysql_config)
        c = dbMysql.cursor(MySQLdb.cursors.DictCursor)
        sql_factory = " SELECT * FROM  `stat_cms_version` order by id desc "
        c.execute(sql_factory)
        entrie = c.fetchone()    
        message = 'ok'
        
        content = ''.join(d.get(c, c) for c in entrie['content'])
        
        dbMysql.close()
        c.close()
        
        riqis = str(entrie['date'])
        
        yy = riqis[0:4]
        mm = riqis[4:6]
        dd = riqis[6:]
        
        riqi = "%s-%s-%s" % (yy,mm,dd)
        
        try:
            #self.write("{ \"title\": \"%s\",\"date\": \"%s\",\"content\": \"%s\"}" % (entrie['title'],riqi,content))
            self.write("{ \"title\": \"%s\",\"date\": \"%s\"}" % (entrie['title'],entrie['versiondate']))
        except:
            self.write("{ \"error\": \"404\"}")
            
            
class ReturnContent(BaseHandler):    
    
    def get(self):         
        mysql_config = settings.mysql_cms_config
        d = {'"':'\\"', "'":"\\'", "\0":"\\\0", "\\":"\\\\"}      
        dbMysql = MySQLdb.connect(**mysql_config)
        c = dbMysql.cursor(MySQLdb.cursors.DictCursor)
        sql_factory = " SELECT * FROM  `stat_cms_version` order by id desc "
        c.execute(sql_factory)
        entrie = c.fetchone()    
        message = 'ok'
        
        #content = ''.join(d.get(c, c) for c in entrie['content'])
        
        fanhui = entrie['content']
        
        dbMysql.close()
        c.close()
        
        riqis = str(entrie['date'])
        
        yy = riqis[0:4]
        mm = riqis[4:6]
        dd = riqis[6:]
        
        riqi = "%s-%s-%s" % (yy,mm,dd)
        
        self.write(fanhui)        


class ReturnTable(BaseHandler):    
    
    def get(self):         
        mysql_config = settings.mysql_cms_config
        d = {'"':'\\"', "'":"\\'", "\0":"\\\0", "\\":"\\\\"}      
        dbMysql = MySQLdb.connect(**mysql_config)
        c = dbMysql.cursor(MySQLdb.cursors.DictCursor)
        sql_factory = " SELECT * FROM  `stat_cms_log` where `show` = '1'  order by id desc "
        c.execute(sql_factory)
        entrie = c.fetchall()    
        
        fanhui=""
        jishu = 0
        
        for x in entrie:
            _id = x['id']
            content = x['content']
            title = x['title']
            
            jishu = jishu + 1
            
            if jishu % 2 == 0:
                fanhui+="<tr class='new_silver_even'><td class=\"new_silver_first_n\" style='text-align:center;'>%s</td><td class=\"\" style=\"text-align:left;\"><a class=\"trigger\" rel=\"targetBox%s\" title='%s' >%s</a><div id=\"targetBox%s\" style=\"display:none;\" class=\"shadow target_box dn\">%s</div></td></tr>" % (jishu,_id,content,title,_id,content)
            else:
                fanhui+="<tr class='new_silver_odd'><td class=\"new_silver_first_n\" style='text-align:center;'>%s</td><td class=\"\" style=\"text-align:left;\"><a class=\"trigger\" rel=\"targetBox%s\" title='%s' >%s</a><div id=\"targetBox%s\" style=\"display:none;\" class=\"shadow target_box dn\">%s</div></td></tr>" % (jishu,_id,content,title,_id,content)
            #print jishu
            
        
        
        
        
        
        self.write(fanhui)




class MainDlPaike(BaseHandler):
    
    def post(self):
        _url = self.request.uri
        _username = self.get_argument('username','nobody').strip()
        common.CollectionUrl(_username,_url)
        self.write("ok")
        self.finish()
    
    def get(self): 
    
    
        _url = self.request.uri
        cnsort.setredis(_url)
        mc = cnsort.setmc()
        _md5 = hashlib.md5(_url)
        _md5.digest()
        _md5_ = _md5.hexdigest()
        m_value = mc.get(_md5.hexdigest()) or {}
        if settings.cache_on == 0:
            m_value = {}
            
        if not m_value:
        
        
            table_name = "stat_store_download_update"
            
            pidtype_json = clientcache.getPidType()
            
            _time = self.get_argument('staDate', '2011/11/13').strip()
            _pd = self.get_argument('pd','').strip()
            
            
            try:
                st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                #self.write({"status": "failed", "code": 400,  "desc": "invalid argument"})
                #self.finish()
                return
            
            if not _pd:
                ed_time = datetime.datetime.now()
                delta = ed_time - st_time 
                _pd =  abs(delta.days)
            _pd = int(_pd)
            et_time = st_time + datetime.timedelta(days=_pd)
            st_datestr = st_time.strftime('%Y%m%d')
            et_datestr = et_time.strftime('%Y%m%d')
            
            all_data = []
            results = {}
            os_data = []
            
            db = connectMySQL.connMySQL_stat()
            c=db.cursor()

            sql = "SELECT date, sum(download_num),sum(update_num),device_id FROM `stat_store_download_update` WHERE date>= '{0}' and date < '{1}'  and app_type = 2   group by date, device_id   ".format(st_datestr, et_datestr)
            logging.info(sql)
            print sql
            c.execute(sql)  
            res= c.fetchall()
            _tmpdate = ''
            
            
            
            for x in res:
                date = str(x[0])
                os = int(x[3])
                download_num = int(x[1])
                update_num = int(x[2])
                
                
                if _tmpdate and _tmpdate != date:
                    results['data'] = os_data
                    results['year'] = _tmpdate[:4]
                    results['month'] = _tmpdate[4:6]
                    results['day'] = _tmpdate[6:]
                    all_data.append(results)
                    results = {}
                    os_data = []
                
                if(os == 1):
                    os = "Phone"
                else:
                    os = "Pad"
                
                
                sql = "SELECT device_id FROM `stat_store_download_update` WHERE date = '%s'  and app_type = 2 and device_id = 1; " % x[0]
                logging.info(sql)
                c.execute(sql)  
                res = c.fetchone()
                
                if res == None:
                    os_data.insert(0,{'os':'Phone', 'downloadnum':0, 'updatenum':0})
                    
                sql = "SELECT device_id FROM `stat_store_download_update` WHERE date = '%s'  and app_type = 2 and device_id = 2; " % x[0]
                logging.info(sql)
                c.execute(sql)  
                res = c.fetchone()
                
                if res == None:
                    os_data.insert(0,{'os':'Pad', 'downloadnum':0, 'updatenum':0})
                
                
                os_data.insert(0,{'os':os, 'downloadnum':download_num, 'updatenum':update_num})         
                _tmpdate = date
            
            if len(os_data) > 0 :
                results['data'] = os_data
                results['year'] = _tmpdate[:4]
                results['month'] = _tmpdate[4:6]
                results['day'] = _tmpdate[6:]
                all_data.append(results)
                results = {}
                os_data = []
            
            c.close()
            db.close()
            try:
                mc.set(_md5_,all_data)
            except:
                pass
        else:
            all_data = m_value
        self.write({"status":"success", "items":all_data})
        self.finish()


        

class FactoryDeviceMode(BaseHandler):
    def get(self): 
        parnter_json = clientcache.getParnter()
        
        _btype = self.get_argument('btype', 'video').strip()
        bt_sql = ""
        if _btype == "video":
            bt_sql = "  2 "
        if _btype == "paike":
            bt_sql = "  4 "
        
        _fid = self.get_argument('fid', 'no').strip()
        _osid = self.get_argument('osid','no').strip()
        _staDate = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd', '7').strip()
        
        _type = self.get_argument('type',"no").strip()
        
        if _fid == "no" or _osid == "no" or _type == "no":
            self.write({"status":"success", "items":"[]"})
        
        if _type == "phone":
            _type = 1
        if _type == "pad":
            _type = 2
        
        if not _pd :
            _pd = 7
        else:
            _pd = int(_pd)
        
        if not _fid or not _osid :
            self.send_error(400, desc='invalid argument')
            #self.write({"status": "failed", "code": 400,  "desc": "invalid argument"})
            #self.finish()
            return
        
        st_time = ''
        et_time = ''
        
        if not _staDate:
            _time = datetime.datetime.now() + datetime.timedelta(days=-1)
            st_time = (_time + datetime.timedelta(days=-_pd)).strftime( '%Y%m%d')
            et_time = _time.strftime( '%Y%m%d')
        else :
            try:
                #st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
                _time = datetime.datetime.strptime(_staDate, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                #self.write({"status": "failed", "code": 400,  "desc": "invalid argument"})
                #self.finish()
                return
            st_time= _time.strftime( '%Y%m%d')
            et_time = (_time + datetime.timedelta(days=_pd)).strftime( '%Y%m%d')
        
        all_data = []
        results = {}
        os_data = []

        db = connectMySQL.connMySQL_stat()
        c=db.cursor()        
        sql = "SELECT date, pv, uv, vv, newuser, pid  FROM `stat_day_factory` WHERE   f_id={0} and os_id={1} and partner_mode=1 and pid_stat=1 and device_type = {2} and business_type = {3} and ver = 'ALL' and prov = 'ALL' and city = 'ALL' group by pid ".format(_fid, _osid,_type,bt_sql)
        logging.info(sql)
        print sql
        c.execute(sql)  
        res= c.fetchall()
        _tmpdate = ''
        for x in res:
            date = str(x[0])
            pv = int(x[1])
            uv = int(x[2])
            vv = int(x[3])
            nu = int(x[4])
            pid = x[5]

            if _tmpdate and _tmpdate != date:
                results['data'] = os_data
                #results['year'] = _tmpdate[:4]
                #results['month'] = _tmpdate[4:6]
                #results['day'] = _tmpdate[6:]
                #all_data.append(results)
                results = {}
                os_data = []
            
            #os_data.insert(0,{'uv':uv, 'nu':nu, 'pid':pid, 'pname':parnter_json.get(pid,['',''])[0], 'ph':parnter_json.get(pid,['',''])[1]})
            all_data.insert(0,{'pid':pid,'device':parnter_json.get(pid,['',''])[1]})
            _tmpdate = date
        
        c.close()
        db.close()
        
        
        
        
        
        
        
        if _fid == "no" or _osid == "no" or _type == "no":
            all_data = [] 
        
        self.write({"status":"success", "items":all_data})
        
        self.finish()
        
class PromoDeviceMode(BaseHandler):
    def get(self): 
        parnter_json = clientcache.getParnter()
        
        _btype = self.get_argument('btype', 'video').strip()
        bt_sql = ""
        if _btype == "video":
            bt_sql = "  2 "
        if _btype == "paike":
            bt_sql = "  4 "
        
        
        _ftype = self.get_argument('ftype',"8").strip()
        
        _fsql = ""
        
        if _ftype == "8":
            _fsql = " 8 "
        if _ftype == "2":
            _fsql = " 2 "
        
        _fid = self.get_argument('fid', 'no').strip()
        _osid = self.get_argument('osid','no').strip()
        _staDate = self.get_argument('staDate', '2011/11/13').strip()
        _pd = self.get_argument('pd', '7').strip()
        
        _type = self.get_argument('type',"no").strip()
        
        if _fid == "no" or _osid == "no" or _type == "no":
            self.write({"status":"success", "items":"[]"})
        
        if _type == "phone":
            _type = 1
        if _type == "pad":
            _type = 2
        
        if not _pd :
            _pd = 7
        else:
            _pd = int(_pd)
        
        if not _fid or not _osid :
            self.send_error(400, desc='invalid argument')
            #self.write({"status": "failed", "code": 400,  "desc": "invalid argument"})
            #self.finish()
            return
        
        st_time = ''
        et_time = ''
        
        if not _staDate:
            _time = datetime.datetime.now() + datetime.timedelta(days=-1)
            st_time = (_time + datetime.timedelta(days=-_pd)).strftime( '%Y%m%d')
            et_time = _time.strftime( '%Y%m%d')
        else :
            try:
                #st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
                _time = datetime.datetime.strptime(_staDate, '%Y/%m/%d')
            except :
                self.send_error(400, desc='invalid argument')
                #self.write({"status": "failed", "code": 400,  "desc": "invalid argument"})
                #self.finish()
                return
            st_time= _time.strftime( '%Y%m%d')
            et_time = (_time + datetime.timedelta(days=_pd)).strftime( '%Y%m%d')
        
        all_data = []
        results = {}
        os_data = []

        db = connectMySQL.connMySQL_stat()
        c=db.cursor()        
        sql = "SELECT date, pv, uv, vv, newuser, pid  FROM `stat_day_channel` WHERE   f_id={0} and os_id={1} and partner_mode=1 and pid_stat=1 and device_type = {2} and business_type = {3} and partner_mode = {4}  and ver = 'ALL' and prov = 'ALL' and city = 'ALL'   group by pid ".format(_fid, _osid,_type,bt_sql,_fsql)
        logging.info(sql)
        print sql
        c.execute(sql)  
        res= c.fetchall()
        _tmpdate = ''
        for x in res:
            date = str(x[0])
            pv = int(x[1])
            uv = int(x[2])
            vv = int(x[3])
            nu = int(x[4])
            pid = x[5]

            if _tmpdate and _tmpdate != date:
                results['data'] = os_data
                #results['year'] = _tmpdate[:4]
                #results['month'] = _tmpdate[4:6]
                #results['day'] = _tmpdate[6:]
                #all_data.append(results)
                results = {}
                os_data = []
            
            #os_data.insert(0,{'uv':uv, 'nu':nu, 'pid':pid, 'pname':parnter_json.get(pid,['',''])[0], 'ph':parnter_json.get(pid,['',''])[1]})
            all_data.insert(0,{'pid':pid,'device':parnter_json.get(pid,['',''])[1]})
            _tmpdate = date
        
        c.close()
        db.close()
        
        
        
        #print all_data
        #test = {"items": [{"year": "2011", "data": [{"pv": 8706151, "vv": 883726, "pid": "749c360516ebe533", "uv": 379018, "pname": "mobile优酷友情合作", "nu": 883726}, {"pv": 23036219, "vv": 2646085, "pid": "749c360516ebe533", "uv": 618283, "pname": "3G门户G浏览器", "nu": 2646085}, {"pv": 20426465, "vv": 10197784, "pid": "749c360516ebe533", "uv": 177077, "pname": "百信手机网外链", "nu": 10197784}, {"pv": 5984380, "vv": 675899.0, "pid": "749c360516ebe533", "uv": 380541, "pname": "航海桌面导航", "nu": 675899.0}], "day": "20", "month": "11"}, {"year": "2011", "data": [{"pv": 7738457, "vv": 788236, "pid": "749c360516ebe533", "uv": 344861, "pname": "mobile优酷友情合作", "nu": 788236}, {"pv": 19551225, "vv": 2101659, "pid": "749c360516ebe533", "uv": 510932, "pname": "3G门户G浏览器", "nu": 2101659}, {"pv": 18427618, "vv": 9257357, "pid": "749c360516ebe533", "uv": 157920, "pname": "百信手机网外链", "nu": 9257357}, {"pv": 5501749, "vv": 607562.0, "pid": "749c360516ebe533", "uv": 346352, "pname": "航海桌面导航", "nu": 607562.0}], "day": "21", "month": "11"}, {"year": "2011", "data": [{"pv": 7954177, "vv": 815959, "pid": "749c360516ebe533", "uv": 349300, "pname": "mobile优酷友情合作", "nu": 815959}, {"pv": 17299241, "vv": 2118076, "pid": "749c360516ebe533", "uv": 501143, "pname": "3G门户G浏览器", "nu": 2118076}, {"pv": 20366128, "vv": 10192610, "pid": "749c360516ebe533", "uv": 162041, "pname": "百信手机网外链", "nu": 10192610}, {"pv": 6219346, "vv": 899602, "pid": "749c360516ebe533", "uv": 363954, "pname": "航海桌面导航", "nu": 899602}], "day": "22", "month": "11"}, {"year": "2011", "data": [{"pv": 7977166, "vv": 842794, "pid": "749c360516ebe533", "uv": 348040, "pname": "mobile优酷友情合作", "nu": 842794}, {"pv": 16584716, "vv": 2097957, "pid": "749c360516ebe533", "uv": 490854, "pname": "3G门户G浏览器", "nu": 2097957}, {"pv": 20198366, "vv": 10391665, "pid": "749c360516ebe533", "uv": 161251, "pname": "百信手机网外链", "nu": 10391665}, {"pv": 5815811, "vv": 696805, "pid": "749c360516ebe533", "uv": 364588, "pname": "航海桌面导航", "nu": 696805}], "day": "23", "month": "11"}, {"year": "2011", "data": [{"pv": 7903879, "vv": 847485, "pid": "749c360516ebe533", "uv": 346739, "pname": "mobile优酷友情合作", "nu": 847485}, {"pv": 15089805, "vv": 2072196, "pid": "749c360516ebe533", "uv": 486514, "pname": "3G门户G浏览器", "nu": 2072196}, {"pv": 21005978, "vv": 10992027, "pid": "749c360516ebe533", "uv": 160747, "pname": "百信手机网外链", "nu": 10992027}, {"pv": 5907725, "vv": 714918, "pid": "749c360516ebe533", "uv": 365872, "pname": "航海桌面导航", "nu": 714918}], "day": "24", "month": "11"}, {"year": "2011", "data": [{"pv": 8036462, "vv": 859703, "pid": "749c360516ebe533", "uv": 351217, "pname": "mobile优酷友情合作", "nu": 859703}, {"pv": 16574256, "vv": 2147187, "pid": "749c360516ebe533", "uv": 508284, "pname": "3G门户G浏览器", "nu": 2147187}, {"pv": 20814242, "vv": 10802160, "pid": "749c360516ebe533", "uv": 166903, "pname": "百信手机网外链", "nu": 10802160}, {"pv": 5869896, "vv": 742478, "pid": "749c360516ebe533", "uv": 370612, "pname": "航海桌面导航", "nu": 742478}], "day": "25", "month": "11"}, {"year": "2011", "data": [{"pv": 9069765, "vv": 972571, "pid": "749c360516ebe533", "uv": 387447, "pname": "mobile优酷友情合作", "nu": 972571}, {"pv": 19110457, "vv": 2686480, "pid": "749c360516ebe533", "uv": 607180, "pname": "3G门户G浏览器", "nu": 2686480}, {"pv": 22990850, "vv": 12016920, "pid": "749c360516ebe533", "uv": 189509, "pname": "百信手机网外链", "nu": 12016920}, {"pv": 6409802, "vv": 819128, "pid": "749c360516ebe533", "uv": 408271, "pname": "航海桌面导航", "nu": 819128}], "day": "26", "month": "11"}, {"year": "2011", "data": [{"pv": 5164029, "vv": 905470, "pid": "749c360516ebe533", "uv": 402251, "pname": "mobile优酷友情合作", "nu": 905470}, {"pv": 22663416, "vv": 2959138, "pid": "749c360516ebe533", "uv": 625509, "pname": "3G门户G浏览器", "nu": 2959138}, {"pv": 22769949, "vv": 12005075, "pid": "749c360516ebe533", "uv": 194499, "pname": "百信手机网外链", "nu": 12005075}, {"pv": 6496387, "vv": 824110, "pid": "749c360516ebe533", "uv": 405406, "pname": "航海桌面导航", "nu": 824110}], "day": "27", "month": "11"}, {"year": "2011", "data": [{"pv": 7883670, "vv": 923891, "pid": "749c360516ebe533", "uv": 364508, "pname": "mobile优酷友情合作", "nu": 923891}, {"pv": 16813831, "vv": 2227148, "pid": "749c360516ebe533", "uv": 523621, "pname": "3G门户G浏览器", "nu": 2227148}, {"pv": 21876510, "vv": 11389919, "pid": "749c360516ebe533", "uv": 177008, "pname": "百信手机网外链", "nu": 11389919}, {"pv": 6182231, "vv": 786666, "pid": "749c360516ebe533", "uv": 377465, "pname": "航海桌面导航", "nu": 786666}], "day": "28", "month": "11"}, {"year": "2011", "data": [{"pv": 8932697, "vv": 979964, "pid": "749c360516ebe533", "uv": 371687, "pname": "mobile优酷友情合作", "nu": 979964}, {"pv": 18295828, "vv": 2271816, "pid": "749c360516ebe533", "uv": 529236, "pname": "3G门户G浏览器", "nu": 2271816}, {"pv": 24524788, "vv": 12383988, "pid": "749c360516ebe533", "uv": 179472, "pname": "百信手机网外链", "nu": 12383988}, {"pv": 7263753, "vv": 960556, "pid": "749c360516ebe533", "uv": 398384, "pname": "航海桌面导航", "nu": 960556}], "day": "29", "month": "11"}, {"year": "2011", "data": [{"pv": 9555887, "vv": 1046894, "pid": "749c360516ebe533", "uv": 383029, "pname": "mobile优酷友情合作", "nu": 1046894}, {"pv": 17147726, "vv": 2320942, "pid": "749c360516ebe533", "uv": 530421, "pname": "3G门户G浏览器", "nu": 2320942}, {"pv": 26100803, "vv": 13301933, "pid": "749c360516ebe533", "uv": 184759, "pname": "百信手机网外链", "nu": 13301933}, {"pv": 7837226, "vv": 1065946, "pid": "749c360516ebe533", "uv": 462942, "pname": "航海桌面导航", "nu": 1065946}], "day": "30", "month": "11"}, {"year": "2011", "data": [{"pv": 9191284, "vv": 997910, "pid": "749c360516ebe533", "uv": 378109, "pname": "mobile优酷友情合作", "nu": 997910}, {"pv": 17538103, "vv": 2212043, "pid": "749c360516ebe533", "uv": 508844, "pname": "3G门户G浏览器", "nu": 2212043}, {"pv": 23764115, "vv": 12167367, "pid": "749c360516ebe533", "uv": 182590, "pname": "百信手机网外链", "nu": 12167367}, {"pv": 7159327, "vv": 898155, "pid": "749c360516ebe533", "uv": 455937, "pname": "航海桌面导航", "nu": 898155}], "day": "01", "month": "12"}, {"year": "2011", "data": [{"pv": 8746707, "vv": 944695, "pid": "749c360516ebe533", "uv": 369130, "pname": "mobile优酷友情合作", "nu": 944695}, {"pv": 20920133, "vv": 2218533, "pid": "749c360516ebe533", "uv": 515960, "pname": "3G门户G浏览器", "nu": 2218533}, {"pv": 22158746, "vv": 11385687, "pid": "749c360516ebe533", "uv": 176859, "pname": "百信手机网外链", "nu": 11385687}, {"pv": 6573226, "vv": 820262, "pid": "749c360516ebe533", "uv": 429128, "pname": "航海桌面导航", "nu": 820262}], "day": "02", "month": "12"}, {"year": "2011", "data": [{"pv": 9729478, "vv": 1075297, "pid": "749c360516ebe533", "uv": 399538, "pname": "mobile优酷友情合作", "nu": 1075297}, {"pv": 25240817, "vv": 2707561, "pid": "749c360516ebe533", "uv": 601559, "pname": "3G门户G浏览器", "nu": 2707561}, {"pv": 23853896, "vv": 12166467, "pid": "749c360516ebe533", "uv": 197107, "pname": "百信手机网外链", "nu": 12166467}, {"pv": 6951907, "vv": 883009, "pid": "749c360516ebe533", "uv": 448783, "pname": "航海桌面导航", "nu": 883009}], "day": "03", "month": "12"}, {"year": "2011", "data": [{"pv": 6553890, "vv": 1000655, "pid": "749c360516ebe533", "uv": 410977, "pname": "mobile优酷友情合作", "nu": 1000655}, {"pv": 26534414, "vv": 2949384, "pid": "749c360516ebe533", "uv": 657332, "pname": "3G门户G浏览器", "nu": 2949384}, {"pv": 20255624, "vv": 9431825, "pid": "749c360516ebe533", "uv": 202836, "pname": "百信手机网外链", "nu": 9431825}, {"pv": 6194333, "vv": 709191, "pid": "749c360516ebe533", "uv": 401298, "pname": "航海桌面导航", "nu": 709191}], "day": "04", "month": "12"}, {"year": "2011", "data": [{"pv": 7504068, "vv": 931829, "pid": "749c360516ebe533", "uv": 372472, "pname": "mobile优酷友情合作", "nu": 931829}, {"pv": 26728075, "vv": 2215458, "pid": "749c360516ebe533", "uv": 556967, "pname": "3G门户G浏览器", "nu": 2215458}, {"pv": 22015006, "vv": 11073917, "pid": "749c360516ebe533", "uv": 181164, "pname": "百信手机网外链", "nu": 11073917}, {"pv": 6398145, "vv": 790298, "pid": "749c360516ebe533", "uv": 404533, "pname": "航海桌面导航", "nu": 790298}], "day": "05", "month": "12"}, {"year": "2011", "data": [{"pv": 9102575, "vv": 1062570, "pid": "749c360516ebe533", "uv": 375255, "pname": "mobile优酷友情合作", "nu": 1062570}, {"pv": 22657579, "vv": 2378515, "pid": "749c360516ebe533", "uv": 519891, "pname": "3G门户G浏览器", "nu": 2378515}, {"pv": 25411025, "vv": 12908338, "pid": "749c360516ebe533", "uv": 183900, "pname": "百信手机网外链", "nu": 12908338}, {"pv": 7267270, "vv": 921841, "pid": "749c360516ebe533", "uv": 431079, "pname": "航海桌面导航", "nu": 921841}], "day": "06", "month": "12"}, {"year": "2011", "data": [{"pv": 9323365, "vv": 1093411, "pid": "749c360516ebe533", "uv": 380987, "pname": "mobile优酷友情合作", "nu": 1093411}, {"pv": 27118625, "vv": 2324804, "pid": "749c360516ebe533", "uv": 509508, "pname": "3G门户G浏览器", "nu": 2324804}, {"pv": 27824591, "vv": 13416846, "pid": "749c360516ebe533", "uv": 201491, "pname": "百信手机网外链", "nu": 13416846}, {"pv": 8086168, "vv": 1000817, "pid": "749c360516ebe533", "uv": 442779, "pname": "航海桌面导航", "nu": 1000817}], "day": "07", "month": "12"}, {"year": "2011", "data": [{"pv": 9038836, "vv": 1063200, "pid": "749c360516ebe533", "uv": 373748, "pname": "mobile优酷友情合作", "nu": 1063200}, {"pv": 17233370, "vv": 2134431, "pid": "749c360516ebe533", "uv": 508371, "pname": "3G门户G浏览器", "nu": 2134431}, {"pv": 26251026, "vv": 12625185, "pid": "749c360516ebe533", "uv": 205565, "pname": "百信手机网外链", "nu": 12625185}, {"pv": 7313013, "vv": 902782, "pid": "749c360516ebe533", "uv": 411684, "pname": "航海桌面导航", "nu": 902782}], "day": "08", "month": "12"}, {"year": "2011", "data": [{"pv": 8363367, "vv": 1045071, "pid": "749c360516ebe533", "uv": 371220, "pname": "mobile优酷友情合作", "nu": 1045071}, {"pv": 17447010, "vv": 2132177, "pid": "749c360516ebe533", "uv": 481472, "pname": "3G门户G浏览器", "nu": 2132177}, {"pv": 23802977, "vv": 11606653, "pid": "749c360516ebe533", "uv": 208438, "pname": "百信手机网外链", "nu": 11606653}, {"pv": 6693872, "vv": 937565, "pid": "749c360516ebe533", "uv": 398948, "pname": "航海桌面导航", "nu": 937565}], "day": "09", "month": "12"}, {"year": "2011", "data": [{"pv": 9525712, "vv": 1127967, "pid": "749c360516ebe533", "uv": 399203, "pname": "mobile优酷友情合作", "nu": 1127967}, {"pv": 21035193, "vv": 2485316, "pid": "749c360516ebe533", "uv": 550803, "pname": "3G门户G浏览器", "nu": 2485316}, {"pv": 26775777, "vv": 12982224, "pid": "749c360516ebe533", "uv": 239143, "pname": "百信手机网外链", "nu": 12982224}, {"pv": 6780413, "vv": 835476, "pid": "749c360516ebe533", "uv": 422789, "pname": "航海桌面导航", "nu": 835476}], "day": "10", "month": "12"}, {"year": "2011", "data": [{"pv": 9700728, "vv": 1156906, "pid": "749c360516ebe533", "uv": 404359, "pname": "mobile优酷友情合作", "nu": 1156906}, {"pv": 18842952, "vv": 2470392, "pid": "749c360516ebe533", "uv": 546650, "pname": "3G门户G浏览器", "nu": 2470392}, {"pv": 27251966, "vv": 13014231, "pid": "749c360516ebe533", "uv": 249194, "pname": "百信手机网外链", "nu": 13014231}, {"pv": 6725342, "vv": 812185, "pid": "749c360516ebe533", "uv": 417197, "pname": "航海桌面导航", "nu": 812185}], "day": "11", "month": "12"}, {"year": "2011", "data": [{"pv": 8318720, "vv": 1010236, "pid": "749c360516ebe533", "uv": 361017, "pname": "mobile优酷友情合作", "nu": 1010236}, {"pv": 12905152, "vv": 1890186, "pid": "749c360516ebe533", "uv": 446430, "pname": "3G门户G浏览器", "nu": 1890186}, {"pv": 24365788, "vv": 11680267, "pid": "749c360516ebe533", "uv": 216079, "pname": "百信手机网外链", "nu": 11680267}, {"pv": 6134800, "vv": 730836, "pid": "749c360516ebe533", "uv": 388648, "pname": "航海桌面导航", "nu": 730836}], "day": "12", "month": "12"}, {"year": "2011", "data": [{"pv": 8689454, "vv": 1069416, "pid": "749c360516ebe533", "uv": 371320, "pname": "mobile优酷友情合作", "nu": 1069416}, {"pv": 14424782, "vv": 1908065, "pid": "749c360516ebe533", "uv": 451278, "pname": "3G门户G浏览器", "nu": 1908065}, {"pv": 25477197, "vv": 12223510, "pid": "749c360516ebe533", "uv": 223816, "pname": "百信手机网外链", "nu": 12223510}, {"pv": 6353900, "vv": 764547, "pid": "749c360516ebe533", "uv": 396732, "pname": "航海桌面导航", "nu": 764547}], "day": "13", "month": "12"}, {"year": "2011", "data": [{"pv": 8762564, "vv": 1100199, "pid": "749c360516ebe533", "uv": 375636, "pname": "mobile优酷友情合作", "nu": 1100199}, {"pv": 15790426, "vv": 1933915, "pid": "749c360516ebe533", "uv": 447268, "pname": "3G门户G浏览器", "nu": 1933915}, {"pv": 25910457, "vv": 12576917, "pid": "749c360516ebe533", "uv": 226918, "pname": "百信手机网外链", "nu": 12576917}, {"pv": 6392187, "vv": 788946, "pid": "749c360516ebe533", "uv": 395650, "pname": "航海桌面导航", "nu": 788946}], "day": "14", "month": "12"}, {"year": "2011", "data": [{"pv": 8648849, "vv": 1117817, "pid": "749c360516ebe533", "uv": 381679, "pname": "mobile优酷友情合作", "nu": 1117817}, {"pv": 14460326, "vv": 1993575, "pid": "749c360516ebe533", "uv": 458094, "pname": "3G门户G浏览器", "nu": 1993575}, {"pv": 26274120, "vv": 12717041, "pid": "749c360516ebe533", "uv": 234441, "pname": "百信手机网外链", "nu": 12717041}, {"pv": 6442292, "vv": 801841, "pid": "749c360516ebe533", "uv": 404290, "pname": "航海桌面导航", "nu": 801841}], "day": "15", "month": "12"}, {"year": "2011", "data": [{"pv": 8974934, "vv": 1135333, "pid": "749c360516ebe533", "uv": 384968, "pname": "mobile优酷友情合作", "nu": 1135333}, {"pv": 14935738, "vv": 1968406, "pid": "749c360516ebe533", "uv": 460287, "pname": "3G门户G浏览器", "nu": 1968406}, {"pv": 26481000, "vv": 12890380, "pid": "749c360516ebe533", "uv": 238530, "pname": "百信手机网外链", "nu": 12890380}, {"pv": 6517663, "vv": 807037, "pid": "749c360516ebe533", "uv": 411766, "pname": "航海桌面导航", "nu": 807037}], "day": "16", "month": "12"}, {"year": "2011", "data": [{"pv": 10026462, "vv": 1236730, "pid": "749c360516ebe533", "uv": 420494, "pname": "mobile优酷友情合作", "nu": 1236730}, {"pv": 17893920, "vv": 2373075, "pid": "749c360516ebe533", "uv": 533109, "pname": "3G门户G浏览器", "nu": 2373075}, {"pv": 29427041, "vv": 14269110, "pid": "749c360516ebe533", "uv": 276155, "pname": "百信手机网外链", "nu": 14269110}, {"pv": 7106385, "vv": 902434, "pid": "749c360516ebe533", "uv": 441599, "pname": "航海桌面导航", "nu": 902434}], "day": "17", "month": "12"}, {"year": "2011", "data": [{"pv": 10245069, "vv": 1289253, "pid": "749c360516ebe533", "uv": 428359, "pname": "mobile优酷友情合作", "nu": 1289253}, {"pv": 16366469, "vv": 2416836, "pid": "749c360516ebe533", "uv": 535023, "pname": "3G门户G浏览器", "nu": 2416836}, {"pv": 30343887, "vv": 14817690, "pid": "749c360516ebe533", "uv": 285791, "pname": "百信手机网外链", "nu": 14817690}, {"pv": 7162604, "vv": 903269, "pid": "749c360516ebe533", "uv": 451413, "pname": "航海桌面导航", "nu": 903269}], "day": "18", "month": "12"}, {"year": "2011", "data": [{"pv": 8928252, "vv": 1110394, "pid": "749c360516ebe533", "uv": 389020, "pname": "mobile优酷友情合作", "nu": 1110394}, {"pv": 12521422, "vv": 1880090, "pid": "749c360516ebe533", "uv": 448916, "pname": "3G门户G浏览器", "nu": 1880090}, {"pv": 26264948, "vv": 12763681, "pid": "749c360516ebe533", "uv": 248776, "pname": "百信手机网外链", "nu": 12763681}, {"pv": 6481151, "vv": 803660, "pid": "749c360516ebe533", "uv": 407620, "pname": "航海桌面导航", "nu": 803660}], "day": "19", "month": "12"}]}
        
        
        
        if _fid == "no" or _osid == "no" or _type == "no":
            all_data = [] 
        
        self.write({"status":"success", "items":all_data})
        
        self.finish()



class FactoryOSComp(BaseHandler):
    def get(self): 
        os_json = clientcache.getOS()
        
        _fid = self.get_argument('fid', '').strip()
        _period = self.get_argument('period', 'w').strip()
        
        _pd = 0
        if _period == 'm':
            _pd = 30
        elif _period == 'q':
            _pd = 90
        elif _period == 'y':
            _pd = 365
        else:
            _pd = 7
            
        if not _fid:
            self.send_error(400, desc='invalid argument')
            #self.write({"status": "failed", "code": 400,  "desc": "invalid argument"})
            #self.finish()
            return
        
        _time = datetime.datetime.now() + datetime.timedelta(days=0)
        st_time = (_time + datetime.timedelta(days=-_pd)).strftime( '%Y%m%d')
        et_time = _time.strftime( '%Y%m%d')

        #print 's:{0} , e:{1}'.format(st_time, et_time)
        
        all_data = []
        results = {}
        os_data = []

        db = connectMySQL.connMySQL_stat()
        c=db.cursor()        
        sql = "SELECT os_id, sum(newuser)  FROM `stat_day_factory` WHERE date>= '{0}' and date < '{1}' and  f_id={2} and partner_mode=1 and pid_stat=1 group by os_id".format(st_time, et_time, _fid)
        logging.info(sql)
        c.execute(sql)  
        res= c.fetchall()
        _tmpdate = ''
        for x in res:
            #print 'tmpdate:{0}'.format(_tmpdate)
            
            os = os_json.get(x[0],'')
            tu = int(x[1])
            
            os_data.insert(0,{'os':os, 'tnu':tu})
        
        c.close()
        db.close()
        
        #print all_data
        #test = {"items": [{"year": "2011", "data": [{"pv": 8706151, "vv": 883726, "pid": "749c360516ebe533", "uv": 379018, "pname": "mobile优酷友情合作", "nu": 883726}, {"pv": 23036219, "vv": 2646085, "pid": "749c360516ebe533", "uv": 618283, "pname": "3G门户G浏览器", "nu": 2646085}, {"pv": 20426465, "vv": 10197784, "pid": "749c360516ebe533", "uv": 177077, "pname": "百信手机网外链", "nu": 10197784}, {"pv": 5984380, "vv": 675899.0, "pid": "749c360516ebe533", "uv": 380541, "pname": "航海桌面导航", "nu": 675899.0}], "day": "20", "month": "11"}, {"year": "2011", "data": [{"pv": 7738457, "vv": 788236, "pid": "749c360516ebe533", "uv": 344861, "pname": "mobile优酷友情合作", "nu": 788236}, {"pv": 19551225, "vv": 2101659, "pid": "749c360516ebe533", "uv": 510932, "pname": "3G门户G浏览器", "nu": 2101659}, {"pv": 18427618, "vv": 9257357, "pid": "749c360516ebe533", "uv": 157920, "pname": "百信手机网外链", "nu": 9257357}, {"pv": 5501749, "vv": 607562.0, "pid": "749c360516ebe533", "uv": 346352, "pname": "航海桌面导航", "nu": 607562.0}], "day": "21", "month": "11"}, {"year": "2011", "data": [{"pv": 7954177, "vv": 815959, "pid": "749c360516ebe533", "uv": 349300, "pname": "mobile优酷友情合作", "nu": 815959}, {"pv": 17299241, "vv": 2118076, "pid": "749c360516ebe533", "uv": 501143, "pname": "3G门户G浏览器", "nu": 2118076}, {"pv": 20366128, "vv": 10192610, "pid": "749c360516ebe533", "uv": 162041, "pname": "百信手机网外链", "nu": 10192610}, {"pv": 6219346, "vv": 899602, "pid": "749c360516ebe533", "uv": 363954, "pname": "航海桌面导航", "nu": 899602}], "day": "22", "month": "11"}, {"year": "2011", "data": [{"pv": 7977166, "vv": 842794, "pid": "749c360516ebe533", "uv": 348040, "pname": "mobile优酷友情合作", "nu": 842794}, {"pv": 16584716, "vv": 2097957, "pid": "749c360516ebe533", "uv": 490854, "pname": "3G门户G浏览器", "nu": 2097957}, {"pv": 20198366, "vv": 10391665, "pid": "749c360516ebe533", "uv": 161251, "pname": "百信手机网外链", "nu": 10391665}, {"pv": 5815811, "vv": 696805, "pid": "749c360516ebe533", "uv": 364588, "pname": "航海桌面导航", "nu": 696805}], "day": "23", "month": "11"}, {"year": "2011", "data": [{"pv": 7903879, "vv": 847485, "pid": "749c360516ebe533", "uv": 346739, "pname": "mobile优酷友情合作", "nu": 847485}, {"pv": 15089805, "vv": 2072196, "pid": "749c360516ebe533", "uv": 486514, "pname": "3G门户G浏览器", "nu": 2072196}, {"pv": 21005978, "vv": 10992027, "pid": "749c360516ebe533", "uv": 160747, "pname": "百信手机网外链", "nu": 10992027}, {"pv": 5907725, "vv": 714918, "pid": "749c360516ebe533", "uv": 365872, "pname": "航海桌面导航", "nu": 714918}], "day": "24", "month": "11"}, {"year": "2011", "data": [{"pv": 8036462, "vv": 859703, "pid": "749c360516ebe533", "uv": 351217, "pname": "mobile优酷友情合作", "nu": 859703}, {"pv": 16574256, "vv": 2147187, "pid": "749c360516ebe533", "uv": 508284, "pname": "3G门户G浏览器", "nu": 2147187}, {"pv": 20814242, "vv": 10802160, "pid": "749c360516ebe533", "uv": 166903, "pname": "百信手机网外链", "nu": 10802160}, {"pv": 5869896, "vv": 742478, "pid": "749c360516ebe533", "uv": 370612, "pname": "航海桌面导航", "nu": 742478}], "day": "25", "month": "11"}, {"year": "2011", "data": [{"pv": 9069765, "vv": 972571, "pid": "749c360516ebe533", "uv": 387447, "pname": "mobile优酷友情合作", "nu": 972571}, {"pv": 19110457, "vv": 2686480, "pid": "749c360516ebe533", "uv": 607180, "pname": "3G门户G浏览器", "nu": 2686480}, {"pv": 22990850, "vv": 12016920, "pid": "749c360516ebe533", "uv": 189509, "pname": "百信手机网外链", "nu": 12016920}, {"pv": 6409802, "vv": 819128, "pid": "749c360516ebe533", "uv": 408271, "pname": "航海桌面导航", "nu": 819128}], "day": "26", "month": "11"}, {"year": "2011", "data": [{"pv": 5164029, "vv": 905470, "pid": "749c360516ebe533", "uv": 402251, "pname": "mobile优酷友情合作", "nu": 905470}, {"pv": 22663416, "vv": 2959138, "pid": "749c360516ebe533", "uv": 625509, "pname": "3G门户G浏览器", "nu": 2959138}, {"pv": 22769949, "vv": 12005075, "pid": "749c360516ebe533", "uv": 194499, "pname": "百信手机网外链", "nu": 12005075}, {"pv": 6496387, "vv": 824110, "pid": "749c360516ebe533", "uv": 405406, "pname": "航海桌面导航", "nu": 824110}], "day": "27", "month": "11"}, {"year": "2011", "data": [{"pv": 7883670, "vv": 923891, "pid": "749c360516ebe533", "uv": 364508, "pname": "mobile优酷友情合作", "nu": 923891}, {"pv": 16813831, "vv": 2227148, "pid": "749c360516ebe533", "uv": 523621, "pname": "3G门户G浏览器", "nu": 2227148}, {"pv": 21876510, "vv": 11389919, "pid": "749c360516ebe533", "uv": 177008, "pname": "百信手机网外链", "nu": 11389919}, {"pv": 6182231, "vv": 786666, "pid": "749c360516ebe533", "uv": 377465, "pname": "航海桌面导航", "nu": 786666}], "day": "28", "month": "11"}, {"year": "2011", "data": [{"pv": 8932697, "vv": 979964, "pid": "749c360516ebe533", "uv": 371687, "pname": "mobile优酷友情合作", "nu": 979964}, {"pv": 18295828, "vv": 2271816, "pid": "749c360516ebe533", "uv": 529236, "pname": "3G门户G浏览器", "nu": 2271816}, {"pv": 24524788, "vv": 12383988, "pid": "749c360516ebe533", "uv": 179472, "pname": "百信手机网外链", "nu": 12383988}, {"pv": 7263753, "vv": 960556, "pid": "749c360516ebe533", "uv": 398384, "pname": "航海桌面导航", "nu": 960556}], "day": "29", "month": "11"}, {"year": "2011", "data": [{"pv": 9555887, "vv": 1046894, "pid": "749c360516ebe533", "uv": 383029, "pname": "mobile优酷友情合作", "nu": 1046894}, {"pv": 17147726, "vv": 2320942, "pid": "749c360516ebe533", "uv": 530421, "pname": "3G门户G浏览器", "nu": 2320942}, {"pv": 26100803, "vv": 13301933, "pid": "749c360516ebe533", "uv": 184759, "pname": "百信手机网外链", "nu": 13301933}, {"pv": 7837226, "vv": 1065946, "pid": "749c360516ebe533", "uv": 462942, "pname": "航海桌面导航", "nu": 1065946}], "day": "30", "month": "11"}, {"year": "2011", "data": [{"pv": 9191284, "vv": 997910, "pid": "749c360516ebe533", "uv": 378109, "pname": "mobile优酷友情合作", "nu": 997910}, {"pv": 17538103, "vv": 2212043, "pid": "749c360516ebe533", "uv": 508844, "pname": "3G门户G浏览器", "nu": 2212043}, {"pv": 23764115, "vv": 12167367, "pid": "749c360516ebe533", "uv": 182590, "pname": "百信手机网外链", "nu": 12167367}, {"pv": 7159327, "vv": 898155, "pid": "749c360516ebe533", "uv": 455937, "pname": "航海桌面导航", "nu": 898155}], "day": "01", "month": "12"}, {"year": "2011", "data": [{"pv": 8746707, "vv": 944695, "pid": "749c360516ebe533", "uv": 369130, "pname": "mobile优酷友情合作", "nu": 944695}, {"pv": 20920133, "vv": 2218533, "pid": "749c360516ebe533", "uv": 515960, "pname": "3G门户G浏览器", "nu": 2218533}, {"pv": 22158746, "vv": 11385687, "pid": "749c360516ebe533", "uv": 176859, "pname": "百信手机网外链", "nu": 11385687}, {"pv": 6573226, "vv": 820262, "pid": "749c360516ebe533", "uv": 429128, "pname": "航海桌面导航", "nu": 820262}], "day": "02", "month": "12"}, {"year": "2011", "data": [{"pv": 9729478, "vv": 1075297, "pid": "749c360516ebe533", "uv": 399538, "pname": "mobile优酷友情合作", "nu": 1075297}, {"pv": 25240817, "vv": 2707561, "pid": "749c360516ebe533", "uv": 601559, "pname": "3G门户G浏览器", "nu": 2707561}, {"pv": 23853896, "vv": 12166467, "pid": "749c360516ebe533", "uv": 197107, "pname": "百信手机网外链", "nu": 12166467}, {"pv": 6951907, "vv": 883009, "pid": "749c360516ebe533", "uv": 448783, "pname": "航海桌面导航", "nu": 883009}], "day": "03", "month": "12"}, {"year": "2011", "data": [{"pv": 6553890, "vv": 1000655, "pid": "749c360516ebe533", "uv": 410977, "pname": "mobile优酷友情合作", "nu": 1000655}, {"pv": 26534414, "vv": 2949384, "pid": "749c360516ebe533", "uv": 657332, "pname": "3G门户G浏览器", "nu": 2949384}, {"pv": 20255624, "vv": 9431825, "pid": "749c360516ebe533", "uv": 202836, "pname": "百信手机网外链", "nu": 9431825}, {"pv": 6194333, "vv": 709191, "pid": "749c360516ebe533", "uv": 401298, "pname": "航海桌面导航", "nu": 709191}], "day": "04", "month": "12"}, {"year": "2011", "data": [{"pv": 7504068, "vv": 931829, "pid": "749c360516ebe533", "uv": 372472, "pname": "mobile优酷友情合作", "nu": 931829}, {"pv": 26728075, "vv": 2215458, "pid": "749c360516ebe533", "uv": 556967, "pname": "3G门户G浏览器", "nu": 2215458}, {"pv": 22015006, "vv": 11073917, "pid": "749c360516ebe533", "uv": 181164, "pname": "百信手机网外链", "nu": 11073917}, {"pv": 6398145, "vv": 790298, "pid": "749c360516ebe533", "uv": 404533, "pname": "航海桌面导航", "nu": 790298}], "day": "05", "month": "12"}, {"year": "2011", "data": [{"pv": 9102575, "vv": 1062570, "pid": "749c360516ebe533", "uv": 375255, "pname": "mobile优酷友情合作", "nu": 1062570}, {"pv": 22657579, "vv": 2378515, "pid": "749c360516ebe533", "uv": 519891, "pname": "3G门户G浏览器", "nu": 2378515}, {"pv": 25411025, "vv": 12908338, "pid": "749c360516ebe533", "uv": 183900, "pname": "百信手机网外链", "nu": 12908338}, {"pv": 7267270, "vv": 921841, "pid": "749c360516ebe533", "uv": 431079, "pname": "航海桌面导航", "nu": 921841}], "day": "06", "month": "12"}, {"year": "2011", "data": [{"pv": 9323365, "vv": 1093411, "pid": "749c360516ebe533", "uv": 380987, "pname": "mobile优酷友情合作", "nu": 1093411}, {"pv": 27118625, "vv": 2324804, "pid": "749c360516ebe533", "uv": 509508, "pname": "3G门户G浏览器", "nu": 2324804}, {"pv": 27824591, "vv": 13416846, "pid": "749c360516ebe533", "uv": 201491, "pname": "百信手机网外链", "nu": 13416846}, {"pv": 8086168, "vv": 1000817, "pid": "749c360516ebe533", "uv": 442779, "pname": "航海桌面导航", "nu": 1000817}], "day": "07", "month": "12"}, {"year": "2011", "data": [{"pv": 9038836, "vv": 1063200, "pid": "749c360516ebe533", "uv": 373748, "pname": "mobile优酷友情合作", "nu": 1063200}, {"pv": 17233370, "vv": 2134431, "pid": "749c360516ebe533", "uv": 508371, "pname": "3G门户G浏览器", "nu": 2134431}, {"pv": 26251026, "vv": 12625185, "pid": "749c360516ebe533", "uv": 205565, "pname": "百信手机网外链", "nu": 12625185}, {"pv": 7313013, "vv": 902782, "pid": "749c360516ebe533", "uv": 411684, "pname": "航海桌面导航", "nu": 902782}], "day": "08", "month": "12"}, {"year": "2011", "data": [{"pv": 8363367, "vv": 1045071, "pid": "749c360516ebe533", "uv": 371220, "pname": "mobile优酷友情合作", "nu": 1045071}, {"pv": 17447010, "vv": 2132177, "pid": "749c360516ebe533", "uv": 481472, "pname": "3G门户G浏览器", "nu": 2132177}, {"pv": 23802977, "vv": 11606653, "pid": "749c360516ebe533", "uv": 208438, "pname": "百信手机网外链", "nu": 11606653}, {"pv": 6693872, "vv": 937565, "pid": "749c360516ebe533", "uv": 398948, "pname": "航海桌面导航", "nu": 937565}], "day": "09", "month": "12"}, {"year": "2011", "data": [{"pv": 9525712, "vv": 1127967, "pid": "749c360516ebe533", "uv": 399203, "pname": "mobile优酷友情合作", "nu": 1127967}, {"pv": 21035193, "vv": 2485316, "pid": "749c360516ebe533", "uv": 550803, "pname": "3G门户G浏览器", "nu": 2485316}, {"pv": 26775777, "vv": 12982224, "pid": "749c360516ebe533", "uv": 239143, "pname": "百信手机网外链", "nu": 12982224}, {"pv": 6780413, "vv": 835476, "pid": "749c360516ebe533", "uv": 422789, "pname": "航海桌面导航", "nu": 835476}], "day": "10", "month": "12"}, {"year": "2011", "data": [{"pv": 9700728, "vv": 1156906, "pid": "749c360516ebe533", "uv": 404359, "pname": "mobile优酷友情合作", "nu": 1156906}, {"pv": 18842952, "vv": 2470392, "pid": "749c360516ebe533", "uv": 546650, "pname": "3G门户G浏览器", "nu": 2470392}, {"pv": 27251966, "vv": 13014231, "pid": "749c360516ebe533", "uv": 249194, "pname": "百信手机网外链", "nu": 13014231}, {"pv": 6725342, "vv": 812185, "pid": "749c360516ebe533", "uv": 417197, "pname": "航海桌面导航", "nu": 812185}], "day": "11", "month": "12"}, {"year": "2011", "data": [{"pv": 8318720, "vv": 1010236, "pid": "749c360516ebe533", "uv": 361017, "pname": "mobile优酷友情合作", "nu": 1010236}, {"pv": 12905152, "vv": 1890186, "pid": "749c360516ebe533", "uv": 446430, "pname": "3G门户G浏览器", "nu": 1890186}, {"pv": 24365788, "vv": 11680267, "pid": "749c360516ebe533", "uv": 216079, "pname": "百信手机网外链", "nu": 11680267}, {"pv": 6134800, "vv": 730836, "pid": "749c360516ebe533", "uv": 388648, "pname": "航海桌面导航", "nu": 730836}], "day": "12", "month": "12"}, {"year": "2011", "data": [{"pv": 8689454, "vv": 1069416, "pid": "749c360516ebe533", "uv": 371320, "pname": "mobile优酷友情合作", "nu": 1069416}, {"pv": 14424782, "vv": 1908065, "pid": "749c360516ebe533", "uv": 451278, "pname": "3G门户G浏览器", "nu": 1908065}, {"pv": 25477197, "vv": 12223510, "pid": "749c360516ebe533", "uv": 223816, "pname": "百信手机网外链", "nu": 12223510}, {"pv": 6353900, "vv": 764547, "pid": "749c360516ebe533", "uv": 396732, "pname": "航海桌面导航", "nu": 764547}], "day": "13", "month": "12"}, {"year": "2011", "data": [{"pv": 8762564, "vv": 1100199, "pid": "749c360516ebe533", "uv": 375636, "pname": "mobile优酷友情合作", "nu": 1100199}, {"pv": 15790426, "vv": 1933915, "pid": "749c360516ebe533", "uv": 447268, "pname": "3G门户G浏览器", "nu": 1933915}, {"pv": 25910457, "vv": 12576917, "pid": "749c360516ebe533", "uv": 226918, "pname": "百信手机网外链", "nu": 12576917}, {"pv": 6392187, "vv": 788946, "pid": "749c360516ebe533", "uv": 395650, "pname": "航海桌面导航", "nu": 788946}], "day": "14", "month": "12"}, {"year": "2011", "data": [{"pv": 8648849, "vv": 1117817, "pid": "749c360516ebe533", "uv": 381679, "pname": "mobile优酷友情合作", "nu": 1117817}, {"pv": 14460326, "vv": 1993575, "pid": "749c360516ebe533", "uv": 458094, "pname": "3G门户G浏览器", "nu": 1993575}, {"pv": 26274120, "vv": 12717041, "pid": "749c360516ebe533", "uv": 234441, "pname": "百信手机网外链", "nu": 12717041}, {"pv": 6442292, "vv": 801841, "pid": "749c360516ebe533", "uv": 404290, "pname": "航海桌面导航", "nu": 801841}], "day": "15", "month": "12"}, {"year": "2011", "data": [{"pv": 8974934, "vv": 1135333, "pid": "749c360516ebe533", "uv": 384968, "pname": "mobile优酷友情合作", "nu": 1135333}, {"pv": 14935738, "vv": 1968406, "pid": "749c360516ebe533", "uv": 460287, "pname": "3G门户G浏览器", "nu": 1968406}, {"pv": 26481000, "vv": 12890380, "pid": "749c360516ebe533", "uv": 238530, "pname": "百信手机网外链", "nu": 12890380}, {"pv": 6517663, "vv": 807037, "pid": "749c360516ebe533", "uv": 411766, "pname": "航海桌面导航", "nu": 807037}], "day": "16", "month": "12"}, {"year": "2011", "data": [{"pv": 10026462, "vv": 1236730, "pid": "749c360516ebe533", "uv": 420494, "pname": "mobile优酷友情合作", "nu": 1236730}, {"pv": 17893920, "vv": 2373075, "pid": "749c360516ebe533", "uv": 533109, "pname": "3G门户G浏览器", "nu": 2373075}, {"pv": 29427041, "vv": 14269110, "pid": "749c360516ebe533", "uv": 276155, "pname": "百信手机网外链", "nu": 14269110}, {"pv": 7106385, "vv": 902434, "pid": "749c360516ebe533", "uv": 441599, "pname": "航海桌面导航", "nu": 902434}], "day": "17", "month": "12"}, {"year": "2011", "data": [{"pv": 10245069, "vv": 1289253, "pid": "749c360516ebe533", "uv": 428359, "pname": "mobile优酷友情合作", "nu": 1289253}, {"pv": 16366469, "vv": 2416836, "pid": "749c360516ebe533", "uv": 535023, "pname": "3G门户G浏览器", "nu": 2416836}, {"pv": 30343887, "vv": 14817690, "pid": "749c360516ebe533", "uv": 285791, "pname": "百信手机网外链", "nu": 14817690}, {"pv": 7162604, "vv": 903269, "pid": "749c360516ebe533", "uv": 451413, "pname": "航海桌面导航", "nu": 903269}], "day": "18", "month": "12"}, {"year": "2011", "data": [{"pv": 8928252, "vv": 1110394, "pid": "749c360516ebe533", "uv": 389020, "pname": "mobile优酷友情合作", "nu": 1110394}, {"pv": 12521422, "vv": 1880090, "pid": "749c360516ebe533", "uv": 448916, "pname": "3G门户G浏览器", "nu": 1880090}, {"pv": 26264948, "vv": 12763681, "pid": "749c360516ebe533", "uv": 248776, "pname": "百信手机网外链", "nu": 12763681}, {"pv": 6481151, "vv": 803660, "pid": "749c360516ebe533", "uv": 407620, "pname": "航海桌面导航", "nu": 803660}], "day": "19", "month": "12"}]}
        self.write({"status":"success", "items":os_data})
        self.finish()

class FactoryComp(BaseHandler):
    def get(self): 
        factory_json = clientcache.getFactoryName()
        
        _osid = self.get_argument('osid', '').strip()
        _period = self.get_argument('period', 'w').strip()
        
        _pd = 0
        if _period == 'm':
            _pd = 30
        elif _period == 'q':
            _pd = 90
        elif _period == 'y':
            _pd = 365
        else:
            _pd = 7
        
        if not _osid:
            self.send_error(400, desc='invalid argument')
            #self.write({"status": "failed", "code": 400,  "desc": "invalid argument"})
            #self.finish()
            return
        
        _time = datetime.datetime.now() + datetime.timedelta(days=0)
        st_time = (_time + datetime.timedelta(days=-_pd)).strftime( '%Y%m%d')
        et_time = _time.strftime( '%Y%m%d')

        #print 's:{0} , e:{1}'.format(st_time, et_time)
        
        all_data = []
        results = {}
        os_data = []

        db = connectMySQL.connMySQL_stat()
        c=db.cursor()
        sql = "SELECT f_id, sum(newuser)  FROM `stat_day_factory` WHERE date>= '{0}' and date < '{1}' and  os_id={2} and partner_mode=1 and pid_stat=1  group by f_id".format(st_time, et_time, _osid)
        logging.info(sql)
        c.execute(sql)  
        res= c.fetchall()
        _tmpdate = ''
        for x in res:
            factory = factory_json.get(x[0],'')
            tu = int(x[1])
            
            os_data.insert(0,{'factory':factory, 'tnu':tu})
        
        c.close()
        db.close()
        
        #print all_data
        #test = {"items": [{"year": "2011", "data": [{"pv": 8706151, "vv": 883726, "pid": "749c360516ebe533", "uv": 379018, "pname": "mobile优酷友情合作", "nu": 883726}, {"pv": 23036219, "vv": 2646085, "pid": "749c360516ebe533", "uv": 618283, "pname": "3G门户G浏览器", "nu": 2646085}, {"pv": 20426465, "vv": 10197784, "pid": "749c360516ebe533", "uv": 177077, "pname": "百信手机网外链", "nu": 10197784}, {"pv": 5984380, "vv": 675899.0, "pid": "749c360516ebe533", "uv": 380541, "pname": "航海桌面导航", "nu": 675899.0}], "day": "20", "month": "11"}, {"year": "2011", "data": [{"pv": 7738457, "vv": 788236, "pid": "749c360516ebe533", "uv": 344861, "pname": "mobile优酷友情合作", "nu": 788236}, {"pv": 19551225, "vv": 2101659, "pid": "749c360516ebe533", "uv": 510932, "pname": "3G门户G浏览器", "nu": 2101659}, {"pv": 18427618, "vv": 9257357, "pid": "749c360516ebe533", "uv": 157920, "pname": "百信手机网外链", "nu": 9257357}, {"pv": 5501749, "vv": 607562.0, "pid": "749c360516ebe533", "uv": 346352, "pname": "航海桌面导航", "nu": 607562.0}], "day": "21", "month": "11"}, {"year": "2011", "data": [{"pv": 7954177, "vv": 815959, "pid": "749c360516ebe533", "uv": 349300, "pname": "mobile优酷友情合作", "nu": 815959}, {"pv": 17299241, "vv": 2118076, "pid": "749c360516ebe533", "uv": 501143, "pname": "3G门户G浏览器", "nu": 2118076}, {"pv": 20366128, "vv": 10192610, "pid": "749c360516ebe533", "uv": 162041, "pname": "百信手机网外链", "nu": 10192610}, {"pv": 6219346, "vv": 899602, "pid": "749c360516ebe533", "uv": 363954, "pname": "航海桌面导航", "nu": 899602}], "day": "22", "month": "11"}, {"year": "2011", "data": [{"pv": 7977166, "vv": 842794, "pid": "749c360516ebe533", "uv": 348040, "pname": "mobile优酷友情合作", "nu": 842794}, {"pv": 16584716, "vv": 2097957, "pid": "749c360516ebe533", "uv": 490854, "pname": "3G门户G浏览器", "nu": 2097957}, {"pv": 20198366, "vv": 10391665, "pid": "749c360516ebe533", "uv": 161251, "pname": "百信手机网外链", "nu": 10391665}, {"pv": 5815811, "vv": 696805, "pid": "749c360516ebe533", "uv": 364588, "pname": "航海桌面导航", "nu": 696805}], "day": "23", "month": "11"}, {"year": "2011", "data": [{"pv": 7903879, "vv": 847485, "pid": "749c360516ebe533", "uv": 346739, "pname": "mobile优酷友情合作", "nu": 847485}, {"pv": 15089805, "vv": 2072196, "pid": "749c360516ebe533", "uv": 486514, "pname": "3G门户G浏览器", "nu": 2072196}, {"pv": 21005978, "vv": 10992027, "pid": "749c360516ebe533", "uv": 160747, "pname": "百信手机网外链", "nu": 10992027}, {"pv": 5907725, "vv": 714918, "pid": "749c360516ebe533", "uv": 365872, "pname": "航海桌面导航", "nu": 714918}], "day": "24", "month": "11"}, {"year": "2011", "data": [{"pv": 8036462, "vv": 859703, "pid": "749c360516ebe533", "uv": 351217, "pname": "mobile优酷友情合作", "nu": 859703}, {"pv": 16574256, "vv": 2147187, "pid": "749c360516ebe533", "uv": 508284, "pname": "3G门户G浏览器", "nu": 2147187}, {"pv": 20814242, "vv": 10802160, "pid": "749c360516ebe533", "uv": 166903, "pname": "百信手机网外链", "nu": 10802160}, {"pv": 5869896, "vv": 742478, "pid": "749c360516ebe533", "uv": 370612, "pname": "航海桌面导航", "nu": 742478}], "day": "25", "month": "11"}, {"year": "2011", "data": [{"pv": 9069765, "vv": 972571, "pid": "749c360516ebe533", "uv": 387447, "pname": "mobile优酷友情合作", "nu": 972571}, {"pv": 19110457, "vv": 2686480, "pid": "749c360516ebe533", "uv": 607180, "pname": "3G门户G浏览器", "nu": 2686480}, {"pv": 22990850, "vv": 12016920, "pid": "749c360516ebe533", "uv": 189509, "pname": "百信手机网外链", "nu": 12016920}, {"pv": 6409802, "vv": 819128, "pid": "749c360516ebe533", "uv": 408271, "pname": "航海桌面导航", "nu": 819128}], "day": "26", "month": "11"}, {"year": "2011", "data": [{"pv": 5164029, "vv": 905470, "pid": "749c360516ebe533", "uv": 402251, "pname": "mobile优酷友情合作", "nu": 905470}, {"pv": 22663416, "vv": 2959138, "pid": "749c360516ebe533", "uv": 625509, "pname": "3G门户G浏览器", "nu": 2959138}, {"pv": 22769949, "vv": 12005075, "pid": "749c360516ebe533", "uv": 194499, "pname": "百信手机网外链", "nu": 12005075}, {"pv": 6496387, "vv": 824110, "pid": "749c360516ebe533", "uv": 405406, "pname": "航海桌面导航", "nu": 824110}], "day": "27", "month": "11"}, {"year": "2011", "data": [{"pv": 7883670, "vv": 923891, "pid": "749c360516ebe533", "uv": 364508, "pname": "mobile优酷友情合作", "nu": 923891}, {"pv": 16813831, "vv": 2227148, "pid": "749c360516ebe533", "uv": 523621, "pname": "3G门户G浏览器", "nu": 2227148}, {"pv": 21876510, "vv": 11389919, "pid": "749c360516ebe533", "uv": 177008, "pname": "百信手机网外链", "nu": 11389919}, {"pv": 6182231, "vv": 786666, "pid": "749c360516ebe533", "uv": 377465, "pname": "航海桌面导航", "nu": 786666}], "day": "28", "month": "11"}, {"year": "2011", "data": [{"pv": 8932697, "vv": 979964, "pid": "749c360516ebe533", "uv": 371687, "pname": "mobile优酷友情合作", "nu": 979964}, {"pv": 18295828, "vv": 2271816, "pid": "749c360516ebe533", "uv": 529236, "pname": "3G门户G浏览器", "nu": 2271816}, {"pv": 24524788, "vv": 12383988, "pid": "749c360516ebe533", "uv": 179472, "pname": "百信手机网外链", "nu": 12383988}, {"pv": 7263753, "vv": 960556, "pid": "749c360516ebe533", "uv": 398384, "pname": "航海桌面导航", "nu": 960556}], "day": "29", "month": "11"}, {"year": "2011", "data": [{"pv": 9555887, "vv": 1046894, "pid": "749c360516ebe533", "uv": 383029, "pname": "mobile优酷友情合作", "nu": 1046894}, {"pv": 17147726, "vv": 2320942, "pid": "749c360516ebe533", "uv": 530421, "pname": "3G门户G浏览器", "nu": 2320942}, {"pv": 26100803, "vv": 13301933, "pid": "749c360516ebe533", "uv": 184759, "pname": "百信手机网外链", "nu": 13301933}, {"pv": 7837226, "vv": 1065946, "pid": "749c360516ebe533", "uv": 462942, "pname": "航海桌面导航", "nu": 1065946}], "day": "30", "month": "11"}, {"year": "2011", "data": [{"pv": 9191284, "vv": 997910, "pid": "749c360516ebe533", "uv": 378109, "pname": "mobile优酷友情合作", "nu": 997910}, {"pv": 17538103, "vv": 2212043, "pid": "749c360516ebe533", "uv": 508844, "pname": "3G门户G浏览器", "nu": 2212043}, {"pv": 23764115, "vv": 12167367, "pid": "749c360516ebe533", "uv": 182590, "pname": "百信手机网外链", "nu": 12167367}, {"pv": 7159327, "vv": 898155, "pid": "749c360516ebe533", "uv": 455937, "pname": "航海桌面导航", "nu": 898155}], "day": "01", "month": "12"}, {"year": "2011", "data": [{"pv": 8746707, "vv": 944695, "pid": "749c360516ebe533", "uv": 369130, "pname": "mobile优酷友情合作", "nu": 944695}, {"pv": 20920133, "vv": 2218533, "pid": "749c360516ebe533", "uv": 515960, "pname": "3G门户G浏览器", "nu": 2218533}, {"pv": 22158746, "vv": 11385687, "pid": "749c360516ebe533", "uv": 176859, "pname": "百信手机网外链", "nu": 11385687}, {"pv": 6573226, "vv": 820262, "pid": "749c360516ebe533", "uv": 429128, "pname": "航海桌面导航", "nu": 820262}], "day": "02", "month": "12"}, {"year": "2011", "data": [{"pv": 9729478, "vv": 1075297, "pid": "749c360516ebe533", "uv": 399538, "pname": "mobile优酷友情合作", "nu": 1075297}, {"pv": 25240817, "vv": 2707561, "pid": "749c360516ebe533", "uv": 601559, "pname": "3G门户G浏览器", "nu": 2707561}, {"pv": 23853896, "vv": 12166467, "pid": "749c360516ebe533", "uv": 197107, "pname": "百信手机网外链", "nu": 12166467}, {"pv": 6951907, "vv": 883009, "pid": "749c360516ebe533", "uv": 448783, "pname": "航海桌面导航", "nu": 883009}], "day": "03", "month": "12"}, {"year": "2011", "data": [{"pv": 6553890, "vv": 1000655, "pid": "749c360516ebe533", "uv": 410977, "pname": "mobile优酷友情合作", "nu": 1000655}, {"pv": 26534414, "vv": 2949384, "pid": "749c360516ebe533", "uv": 657332, "pname": "3G门户G浏览器", "nu": 2949384}, {"pv": 20255624, "vv": 9431825, "pid": "749c360516ebe533", "uv": 202836, "pname": "百信手机网外链", "nu": 9431825}, {"pv": 6194333, "vv": 709191, "pid": "749c360516ebe533", "uv": 401298, "pname": "航海桌面导航", "nu": 709191}], "day": "04", "month": "12"}, {"year": "2011", "data": [{"pv": 7504068, "vv": 931829, "pid": "749c360516ebe533", "uv": 372472, "pname": "mobile优酷友情合作", "nu": 931829}, {"pv": 26728075, "vv": 2215458, "pid": "749c360516ebe533", "uv": 556967, "pname": "3G门户G浏览器", "nu": 2215458}, {"pv": 22015006, "vv": 11073917, "pid": "749c360516ebe533", "uv": 181164, "pname": "百信手机网外链", "nu": 11073917}, {"pv": 6398145, "vv": 790298, "pid": "749c360516ebe533", "uv": 404533, "pname": "航海桌面导航", "nu": 790298}], "day": "05", "month": "12"}, {"year": "2011", "data": [{"pv": 9102575, "vv": 1062570, "pid": "749c360516ebe533", "uv": 375255, "pname": "mobile优酷友情合作", "nu": 1062570}, {"pv": 22657579, "vv": 2378515, "pid": "749c360516ebe533", "uv": 519891, "pname": "3G门户G浏览器", "nu": 2378515}, {"pv": 25411025, "vv": 12908338, "pid": "749c360516ebe533", "uv": 183900, "pname": "百信手机网外链", "nu": 12908338}, {"pv": 7267270, "vv": 921841, "pid": "749c360516ebe533", "uv": 431079, "pname": "航海桌面导航", "nu": 921841}], "day": "06", "month": "12"}, {"year": "2011", "data": [{"pv": 9323365, "vv": 1093411, "pid": "749c360516ebe533", "uv": 380987, "pname": "mobile优酷友情合作", "nu": 1093411}, {"pv": 27118625, "vv": 2324804, "pid": "749c360516ebe533", "uv": 509508, "pname": "3G门户G浏览器", "nu": 2324804}, {"pv": 27824591, "vv": 13416846, "pid": "749c360516ebe533", "uv": 201491, "pname": "百信手机网外链", "nu": 13416846}, {"pv": 8086168, "vv": 1000817, "pid": "749c360516ebe533", "uv": 442779, "pname": "航海桌面导航", "nu": 1000817}], "day": "07", "month": "12"}, {"year": "2011", "data": [{"pv": 9038836, "vv": 1063200, "pid": "749c360516ebe533", "uv": 373748, "pname": "mobile优酷友情合作", "nu": 1063200}, {"pv": 17233370, "vv": 2134431, "pid": "749c360516ebe533", "uv": 508371, "pname": "3G门户G浏览器", "nu": 2134431}, {"pv": 26251026, "vv": 12625185, "pid": "749c360516ebe533", "uv": 205565, "pname": "百信手机网外链", "nu": 12625185}, {"pv": 7313013, "vv": 902782, "pid": "749c360516ebe533", "uv": 411684, "pname": "航海桌面导航", "nu": 902782}], "day": "08", "month": "12"}, {"year": "2011", "data": [{"pv": 8363367, "vv": 1045071, "pid": "749c360516ebe533", "uv": 371220, "pname": "mobile优酷友情合作", "nu": 1045071}, {"pv": 17447010, "vv": 2132177, "pid": "749c360516ebe533", "uv": 481472, "pname": "3G门户G浏览器", "nu": 2132177}, {"pv": 23802977, "vv": 11606653, "pid": "749c360516ebe533", "uv": 208438, "pname": "百信手机网外链", "nu": 11606653}, {"pv": 6693872, "vv": 937565, "pid": "749c360516ebe533", "uv": 398948, "pname": "航海桌面导航", "nu": 937565}], "day": "09", "month": "12"}, {"year": "2011", "data": [{"pv": 9525712, "vv": 1127967, "pid": "749c360516ebe533", "uv": 399203, "pname": "mobile优酷友情合作", "nu": 1127967}, {"pv": 21035193, "vv": 2485316, "pid": "749c360516ebe533", "uv": 550803, "pname": "3G门户G浏览器", "nu": 2485316}, {"pv": 26775777, "vv": 12982224, "pid": "749c360516ebe533", "uv": 239143, "pname": "百信手机网外链", "nu": 12982224}, {"pv": 6780413, "vv": 835476, "pid": "749c360516ebe533", "uv": 422789, "pname": "航海桌面导航", "nu": 835476}], "day": "10", "month": "12"}, {"year": "2011", "data": [{"pv": 9700728, "vv": 1156906, "pid": "749c360516ebe533", "uv": 404359, "pname": "mobile优酷友情合作", "nu": 1156906}, {"pv": 18842952, "vv": 2470392, "pid": "749c360516ebe533", "uv": 546650, "pname": "3G门户G浏览器", "nu": 2470392}, {"pv": 27251966, "vv": 13014231, "pid": "749c360516ebe533", "uv": 249194, "pname": "百信手机网外链", "nu": 13014231}, {"pv": 6725342, "vv": 812185, "pid": "749c360516ebe533", "uv": 417197, "pname": "航海桌面导航", "nu": 812185}], "day": "11", "month": "12"}, {"year": "2011", "data": [{"pv": 8318720, "vv": 1010236, "pid": "749c360516ebe533", "uv": 361017, "pname": "mobile优酷友情合作", "nu": 1010236}, {"pv": 12905152, "vv": 1890186, "pid": "749c360516ebe533", "uv": 446430, "pname": "3G门户G浏览器", "nu": 1890186}, {"pv": 24365788, "vv": 11680267, "pid": "749c360516ebe533", "uv": 216079, "pname": "百信手机网外链", "nu": 11680267}, {"pv": 6134800, "vv": 730836, "pid": "749c360516ebe533", "uv": 388648, "pname": "航海桌面导航", "nu": 730836}], "day": "12", "month": "12"}, {"year": "2011", "data": [{"pv": 8689454, "vv": 1069416, "pid": "749c360516ebe533", "uv": 371320, "pname": "mobile优酷友情合作", "nu": 1069416}, {"pv": 14424782, "vv": 1908065, "pid": "749c360516ebe533", "uv": 451278, "pname": "3G门户G浏览器", "nu": 1908065}, {"pv": 25477197, "vv": 12223510, "pid": "749c360516ebe533", "uv": 223816, "pname": "百信手机网外链", "nu": 12223510}, {"pv": 6353900, "vv": 764547, "pid": "749c360516ebe533", "uv": 396732, "pname": "航海桌面导航", "nu": 764547}], "day": "13", "month": "12"}, {"year": "2011", "data": [{"pv": 8762564, "vv": 1100199, "pid": "749c360516ebe533", "uv": 375636, "pname": "mobile优酷友情合作", "nu": 1100199}, {"pv": 15790426, "vv": 1933915, "pid": "749c360516ebe533", "uv": 447268, "pname": "3G门户G浏览器", "nu": 1933915}, {"pv": 25910457, "vv": 12576917, "pid": "749c360516ebe533", "uv": 226918, "pname": "百信手机网外链", "nu": 12576917}, {"pv": 6392187, "vv": 788946, "pid": "749c360516ebe533", "uv": 395650, "pname": "航海桌面导航", "nu": 788946}], "day": "14", "month": "12"}, {"year": "2011", "data": [{"pv": 8648849, "vv": 1117817, "pid": "749c360516ebe533", "uv": 381679, "pname": "mobile优酷友情合作", "nu": 1117817}, {"pv": 14460326, "vv": 1993575, "pid": "749c360516ebe533", "uv": 458094, "pname": "3G门户G浏览器", "nu": 1993575}, {"pv": 26274120, "vv": 12717041, "pid": "749c360516ebe533", "uv": 234441, "pname": "百信手机网外链", "nu": 12717041}, {"pv": 6442292, "vv": 801841, "pid": "749c360516ebe533", "uv": 404290, "pname": "航海桌面导航", "nu": 801841}], "day": "15", "month": "12"}, {"year": "2011", "data": [{"pv": 8974934, "vv": 1135333, "pid": "749c360516ebe533", "uv": 384968, "pname": "mobile优酷友情合作", "nu": 1135333}, {"pv": 14935738, "vv": 1968406, "pid": "749c360516ebe533", "uv": 460287, "pname": "3G门户G浏览器", "nu": 1968406}, {"pv": 26481000, "vv": 12890380, "pid": "749c360516ebe533", "uv": 238530, "pname": "百信手机网外链", "nu": 12890380}, {"pv": 6517663, "vv": 807037, "pid": "749c360516ebe533", "uv": 411766, "pname": "航海桌面导航", "nu": 807037}], "day": "16", "month": "12"}, {"year": "2011", "data": [{"pv": 10026462, "vv": 1236730, "pid": "749c360516ebe533", "uv": 420494, "pname": "mobile优酷友情合作", "nu": 1236730}, {"pv": 17893920, "vv": 2373075, "pid": "749c360516ebe533", "uv": 533109, "pname": "3G门户G浏览器", "nu": 2373075}, {"pv": 29427041, "vv": 14269110, "pid": "749c360516ebe533", "uv": 276155, "pname": "百信手机网外链", "nu": 14269110}, {"pv": 7106385, "vv": 902434, "pid": "749c360516ebe533", "uv": 441599, "pname": "航海桌面导航", "nu": 902434}], "day": "17", "month": "12"}, {"year": "2011", "data": [{"pv": 10245069, "vv": 1289253, "pid": "749c360516ebe533", "uv": 428359, "pname": "mobile优酷友情合作", "nu": 1289253}, {"pv": 16366469, "vv": 2416836, "pid": "749c360516ebe533", "uv": 535023, "pname": "3G门户G浏览器", "nu": 2416836}, {"pv": 30343887, "vv": 14817690, "pid": "749c360516ebe533", "uv": 285791, "pname": "百信手机网外链", "nu": 14817690}, {"pv": 7162604, "vv": 903269, "pid": "749c360516ebe533", "uv": 451413, "pname": "航海桌面导航", "nu": 903269}], "day": "18", "month": "12"}, {"year": "2011", "data": [{"pv": 8928252, "vv": 1110394, "pid": "749c360516ebe533", "uv": 389020, "pname": "mobile优酷友情合作", "nu": 1110394}, {"pv": 12521422, "vv": 1880090, "pid": "749c360516ebe533", "uv": 448916, "pname": "3G门户G浏览器", "nu": 1880090}, {"pv": 26264948, "vv": 12763681, "pid": "749c360516ebe533", "uv": 248776, "pname": "百信手机网外链", "nu": 12763681}, {"pv": 6481151, "vv": 803660, "pid": "749c360516ebe533", "uv": 407620, "pname": "航海桌面导航", "nu": 803660}], "day": "19", "month": "12"}]}
        self.write({"status":"success", "items":os_data})
        self.finish()
